Java solution


  • 0
    T

    //[1,2,3,2,5]
    find the point (buy, sell) => (0, 2) and (3, 4)

    public class Solution {
        public int maxProfit(int[] prices) {
            int res = 0;
            int N = prices.length;
            int buy = 0, sell = 0;
            boolean hasBuy = false;
            for (int i = 0; i <= N - 2; i++) {
                if (prices[i] <= prices[i + 1]) {
                    if (hasBuy == false) {
                        buy = i; //find the buy point
                        hasBuy = true;
                    }
                    if (i == N - 2) {
                        sell = i + 1; //deal with the last one
                        res += prices[sell] - prices[buy];
                        hasBuy = false;
                    }
                } else if (prices[i] > prices[i + 1] && hasBuy){
                    sell = i; //find the sell point
                    res += prices[sell] - prices[buy];
                    hasBuy = false;
                }
            }
            return res;
        }
    }
    

  • 0
    I

    Great answer,It is simple and great,How could you find it.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.