Advertisement
Guest User

Untitled

a guest
Aug 17th, 2019
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.69 KB | None | 0 0
  1. class Solution {
  2.     public int maxProfit(int[] prices) {
  3.         int n = prices.length;
  4.         int min = Integer.MAX_VALUE, maxProfit = 0;
  5.         int i = -1, buyIndex = -1, sellIndex = -1;
  6.         for (int x = 0; x < n; x++) {
  7.             if (min > prices[x]) {
  8.                 min = prices[x];
  9.                 i = x;
  10.             } else if (maxProfit < prices[x] - min) {
  11.                 maxProfit = prices[x] - min;
  12.                 sellIndex = x;
  13.                 buyIndex = i;
  14.             }
  15.         }
  16.         if (maxProfit == 0) return 0;
  17.         return maxProfit + maxProfit(Arrays.copyOfRange(prices, 0, buyIndex - 1)) + maxProfit(Arrays.copyOfRange(prices, sellIndex+1, n-1));
  18.     }
  19. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement