Jump game

Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
For example:
Given array A = [2,3,1,1,4]
The minimum number of jumps to reach the last index is 2. (Jump 1 step from  index 0 to 1, then 3 steps to the last index.)

C++:
01 int jump(int A[],int n)
02 {
03     int k=0;
04     int prv=0;
05     int far=0;
06     while(far<n1){
07         int tmp=far;
08         for(int i=prv;i<=tmp;i++){
09             if((i+A[i])>far)
10                 far=i+A[i];
11             if(far>n1)
12                     far=n1;
13         }
14         prv=tmp;
15         k++;
16     }
17     return k;
18 }
Advertisements
This entry was posted in Greedy algorithm. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s