Sometimes GREED tricks U

·

1 min read

I was solving this leetcode problem 746. Min Cost Climbing Stairs I thought this problem can be solved by using the greedy method...

the following was my approach of the greedy problem

    1. first select the starting address according to the minimum value
    2. move to startingIndex+1 || startingIndex+2 according to the minimum value
    3. and repeat until you have completed the array and add cost to final ans

Above approach worked for [10,15,20] but not for [0,1,2,2]:

following is the flow for [0,1,2,2]:

0,0 => 1,1 => 3,3 #(index,cost)

But the following is the correct approach:

Go to => (0,0) => (2,2) => over

So greedy algorithm tricked me but dynamic programming saved me

int min(int a,int b)
{
    if(a<b) return a; else return b;
}

int minCostClimbingStairs(int* cost, int costSize)
{
    int n=costSize;
    int f[n+1];


    long int i;
    f[0]=cost[0];
    f[1]=cost[1];

   for(i=2;i<n;i++){
       f[i]=min(f[i-1],f[i-2])+cost[i];
   }

    return min(f[n-1],f[n-2]);
}