1. class Solution {
  2. /**
  3.   there are only two ways to arrive at step i:
  4.   From step i-1
  5.   From step i-2
  6.  
  7.   Path 1: From i-1
  8.   Cost to reach i-1 is prev1.
  9.   you step on i, so you must pay cost[i].
  10.   total cost: prev1 + cost[i]
  11.  
  12.   Path 2: From i-2
  13.   Cost to reach i-2 is prev2.
  14.   you step on i, so you must pay cost[i].
  15.   total cost: prev2 + cost[i]
  16.  
  17.   best way to reach this ith step = cost of this ith step + the cheapest way to reach the previous reachable step.
  18.   currentCost = cost[i] + Math.min(prev1, prev2)
  19.   And update both prev1 and prev2 accordingly
  20.   */
  21. public int minCostClimbingStairs(int[] cost) {
  22. int prev1 = cost[1];
  23. int prev2 = cost[0];
  24.  
  25. for(int i=2; i<cost.length; i++)
  26. {
  27. int currentCost = cost[i] + Math.min(prev1, prev2);
  28. prev2 = prev1;
  29. prev1 = currentCost;
  30. }
  31.  
  32. return Math.min(prev1, prev2);
  33. }
  34. }