Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public int maxProfit(int[] prices) {
- int n = prices.length;
- int min = Integer.MAX_VALUE, maxProfit = 0;
- int i = -1, buyIndex = -1, sellIndex = -1;
- for (int x = 0; x < n; x++) {
- if (min > prices[x]) {
- min = prices[x];
- i = x;
- } else if (maxProfit < prices[x] - min) {
- maxProfit = prices[x] - min;
- sellIndex = x;
- buyIndex = i;
- }
- }
- if (maxProfit == 0) return 0;
- return maxProfit + maxProfit(Arrays.copyOfRange(prices, 0, buyIndex - 1)) + maxProfit(Arrays.copyOfRange(prices, sellIndex+1, n-1));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement