Saturday 4 August 2012

Find least jumps to reach end of the array: Given an array of Integers,if u are on ith element u can make max arr jumps. If i am at an element with value zero, i cannot move forward.find the least selection to reach end of the array. ex: 1 3 5 8 9 2 6 7 6 8 9 starting with arr[0] i can only make one jump to 3, from 3 i can jump either 1 step 0r 2 steps 0r 3 steps.


#include<iostream.h>
#include<conio.h>
int search(int *arr,int start,int end)
{
      int max=arr[start];
      int pos;
      for(int i=start+1;i<=end;i++)
      {
            if(max<arr[i])
            {
                  pos=i;
                  max=arr[i];
            }
      }
      return pos;
}


void main()
{
      clrscr();
      int array[]={1,3,5,4,3,2,6,7,6,8,9};
      int len=11;
      int pos;
      cout<<array[0]<<"  ";
      for(int i=0;i<len;)
      {
            pos=search(array,i,array[i]+i);
            i=pos;
            cout<<"  "<<array[pos];
            if(len-i>array[i])
                  continue;
            else
                  break;
      }
      getch();
}

No comments:

Post a Comment