my java solution and explantion


  • 0
    L

    public int maxProfit(int[] prices) {
    if(prices == null || prices.length <= 1) return 0;
    int profit = 0;
    for(int i = 0; i< prices.length - 1; i++){
    if(prices[i+1] > prices[i]){
    profit += prices[i + 1] - prices[i];
    }
    }
    return profit;
    }

    it is about buy stock and sell stock; as we all know that stock has high points and has low points; if we want make most money we should buy it in the lowest point and sell it on the highest point;

    for example the prices is [1,2,3]; the lowest is 1 and the highest is 3; so max profit = 3 - 1 == 3 - 2 -1 = 2; and there is something math behind this:
    [a1,a2,a3,a4,a5] (a[i] < a[i+1]) and we can found that: (a2-a1) + (a3-a2) + (a4-a3)+(a5 -a4) = a5 - a1; a5 is the highest point and a1 the lowest point;

    so if want make most money just buy it low and sell it high;

    i hope it can help somebody


Log in to reply
 

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