Post a straightforward solution here, forget where I get it.


  • 0
    Y
    class Solution {
    public:
        int jump(vector<int>& nums) {
            int count = 0, max = 0;
            for (int i = 0, nextMax = 0; i <= max && i < nums.size() - 1; i++) {
                nextMax = std::max(nextMax, i + nums[i]);
                if (i == max) {
                    max = nextMax;
                    count++;
                }
            }
            // if there is no way to get to the end, return -1
            return max >= nums.size() - 1 ? count : -1;
        }
    };

Log in to reply
 

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