Jump Game Two

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.)

01 int jump(int A[], int n)
02  {
03      if(n==1)
04          return 0;
05      int prv=0;
06      int far=0;
07      int max=0;
08      int step=1;
09      while(true){
10          for(int i=prv;i<=far;i++){
11              if(i+A[i]>max)
12                  max=i+A[i];
13          }
14          if(max>=n1)
15              return step;
16          if(max==far)
17              return 1;
18          prv=far;
19          far=max;
20          step++;
21      }
22 }
This entry was posted in Dynamic programming. 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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s