C++ O(N) greedy solution


  • 0
    H
    class Solution {
    public:
        int jump(vector<int>& nums) {
            int n = nums.size();
            if(n <= 1) return 0;
            int currentMax = 0, nextMax = 0, i = 0, ans = 0;
            while(1) {
                ans ++;
                for(; i <= currentMax; i ++) {
                    nextMax = max(nextMax, i + nums[i]);
                    if(nextMax >= n - 1) return ans;
                }
                currentMax = nextMax;
            }
            return ans;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.