Leetcode---55. Jump Game

Source: Internet
Author: User

Topic Link: Jump Game

Given an array of non-negative integers, you is initially positioned at the first index of the array.

Each element of the array represents your maximum jump length is at that position.

Determine if you is able to reach the last index.

For example:

The requirement of this problem is given an array of integers, and the array elements represent the maximum distance each can jump. Then the initial position in the first element of the array returns whether the number reaches the last element.

Using the idea of greed, using reach variable maintenance can reach the furthest distance, that is, the global optimal solution. When traversing to I, the local optimal solution is a[i]+i, so the global optimal solution at this time is the maximum of reach and a[i]+i: Reach = Max (reach, A[i] + i).

And the Jump Game II problem, which is the ascent of this question, requires calculating the minimum number of steps to reach the last element.

Time complexity: O (N)

Space complexity: O (1)

1 class Solution2 {3  Public:4     BOOL Canjump(int A[], int N)5     {6         int reach = 0;7          for(int I = 0; I <= reach && I < N; ++ I)8             reach = Max(reach, A[I] + I);9         Ten         return reach >= N - 1; One     } A };

Reprint please indicate source: Leetcode---55. Jump Game

Leetcode---55. Jump Game

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.