Advertisement
Guest User

Untitled

a guest
Oct 13th, 2015
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.09 KB | None | 0 0
  1.  public int maxProfit(int[] prices) {
  2.         if (prices.length < 2) {
  3.             return 0;
  4.         }
  5.         int [] profit = new int[prices.length + 1];
  6.         int [] sold_for = new int[prices.length];
  7.         profit[0] = 0;
  8.         profit[1] = 0;
  9.         for (int i = 1; i < prices.length; i++) {
  10.             if (prices[i] > prices[i-1]) {
  11.                 // can sell
  12.                 int additionalProfit = prices[i] - prices[i-1];
  13.                 sold_for[i-1] = prices[i];
  14.                 for (int j = i - 2; j >= 0; j--) {
  15.                     if (prices[j] >= prices[i]) {
  16.                         // got to a point where there was a point where the max > curr
  17.                         break;
  18.                     }
  19.                     additionalProfit += prices[i] - prices[j] - sold_for[j];
  20.                     sold_for[j] = prices[i];
  21.                    
  22.                 }
  23.                 profit[i + 1] = profit[i] + additionalProfit;
  24.             }
  25.             else {
  26.                 profit[i + 1] = profit[i];
  27.             }
  28.         }
  29.         return profit[prices.length];
  30.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement