Untitled

mail@pastecode.io avatar
unknown
plain_text
3 years ago
846 B
2
Indexable
Never

class Solution{
  public:
    int minJumps(int arr[], int n){
        int count = 0, place_index = 0, jump = arr[0];
        int local_max, local_index;
        
        while (place_index + jump < n) {
            if (arr[place_index] == 0)
                return -1;
                
            local_max = -1;
            local_index = 0;
            for (int i = 1; i <= jump; i++) {
                if (local_max < (arr[i + place_index] + i) && arr[i + place_index] != 0)
                    local_max = arr[i + place_index] + i;
                    local_index = i;
            }
            
            if (local_max == -1)
                return -1;
                
            count++;
            place_index = local_index + place_index;
            jump = arr[place_index];
        }
        count++;
        return count;
    }
};