Advertisement
ogv

Untitled

ogv
Oct 28th, 2019
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.66 KB | None | 0 0
  1. // Runtime: 1 ms, faster than 99.85% of Java online submissions for Best Time to Buy and Sell Stock III.
  2. // Memory Usage: 36.9 MB, less than 100.00% of Java online submissions for Best Time to Buy and Sell Stock III.
  3. class Solution {
  4.     public int maxProfit(int[] prices) {
  5.         int[] sell = { 0, 0 };
  6.         int[] profit =  {0, 0 };
  7.        
  8.         for (int i = prices.length - 1; i >= 0; i--)
  9.             for (int j = 0; j < 2; j++) {
  10.                 profit[j] = Math.max(profit[j], -prices[i] + sell[j]);
  11.                 sell[j] = Math.max(sell[j], prices[i] + (j > 0 ? profit[j - 1]: 0));
  12.             }        
  13.        
  14.         return profit[1];
  15.     }
  16. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement