Sharing my really simple C++ solution


  • 0
    Z
    bool canJump(int A[], int n) {
        if(n == 0){
            return true;
        }
        int maxReachPos = A[0];
        for(int i = 0; i <= maxReachPos; i++){
            if(maxReachPos >= n - 1){
                return true;
            }
            maxReachPos = max(maxReachPos, i + A[i]);
        }
        return false;
    }
    

    The variable maxReachPos indicates the farthest position you can reach.

    At the very beginning, maxReachPos is equal to A[0], which is apparently correct.

    If maxReachPos >= n - 1, then we know we can reach the end point. Therefore, return True.

    Else, keep updating maxReachPos.

    If maxReachPos is always less than n - 1, then return False.

    Please let me know if you think there is any improvements.


Log in to reply
 

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