classSolution{public:intmaxJumps(vector<int>&arr,intd){constintn=arr.size();// dp[i] := the maximum jumps starting from arr[i]vector<int>dp(n,1);// a dcreasing stack that stores indicesstack<int>stack;for(inti=0;i<=n;++i){while(!stack.empty()&&(i==n||arr[stack.top()]<arr[i])){vector<int>indices{stack.top()};stack.pop();while(!stack.empty()&&arr[stack.top()]==arr[indices[0]])indices.push_back(stack.top()),stack.pop();for(constintj:indices){if(i<n&&i-j<=d)// Can jump from i to j.dp[i]=max(dp[i],dp[j]+1);if(!stack.empty()&&j-stack.top()<=d)// Can jump from stack[-1] to j.dp[stack.top()]=max(dp[stack.top()],dp[j]+1);}}stack.push(i);}returnranges::max(dp);}};
classSolution{publicintmaxJumps(int[]arr,intd){finalintn=arr.length;// dp[i] := the maximum jumps starting from arr[i]int[]dp=newint[n];// a dcreasing stack that stores indicesDeque<Integer>stack=newArrayDeque<>();for(inti=0;i<=n;++i){while(!stack.isEmpty()&&(i==n||arr[stack.peek()]<arr[i])){List<Integer>indices=newArrayList<>(List.of(stack.pop()));while(!stack.isEmpty()&&arr[stack.peek()]==arr[indices.get(0)])indices.add(stack.pop());for(finalintj:indices){if(i<n&&i-j<=d)// Can jump from i to j.dp[i]=Math.max(dp[i],dp[j]+1);if(!stack.isEmpty()&&j-stack.peek()<=d)// Can jump from stack.peek() to jdp[stack.peek()]=Math.max(dp[stack.peek()],dp[j]+1);}}stack.push(i);}returnArrays.stream(dp).max().getAsInt()+1;}}
1 2 3 4 5 6 7 8 91011121314151617181920212223
classSolution:defmaxJumps(self,arr:list[int],d:int)->int:n=len(arr)# dp[i] := the maximum jumps starting from arr[i]dp=[1]*n# a dcreasing stack that stores indicesstack=[]foriinrange(n+1):whilestackand(i==norarr[stack[-1]]<arr[i]):indices=[stack.pop()]whilestackandarr[stack[-1]]==arr[indices[0]]:indices.append(stack.pop())forjinindices:ifi<nandi-j<=d:# Can jump from i to j.dp[i]=max(dp[i],dp[j]+1)ifstackandj-stack[-1]<=d:# Can jump from stack[-1] to jdp[stack[-1]]=max(dp[stack[-1]],dp[j]+1)stack.append(i)returnmax(dp)
Thanks for stopping by! If you find this site helpful, consider buying me some protein powder to keep me fueled! π