leetcode

Best Time to Buy and Sell Stock II

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

The idea to find all the ascending sequence, then sum all differences in the ascending sequence.

Because 5,1,0,2,3. since[5,1,0] is descending, we know buy at 0 is best, then [0,2,3] is ascending, we know sell at 3 is best. And (3-0) = (2-0) + (3-2) = 3.

public int maxProfitII(int[] prices) {
        //input prices must have more than one value
        if (prices==null || prices.length<2) {
            return 0;
        }
        int maxProfit = 0;
        int previous = prices[0];
        for (int i=1; i<prices.length; i++) {
            int delta = prices[i]-previous;
            if (delta>0) {
                maxProfit += delta;
            }
            previous = prices[i];
        }
        return maxProfit;
    }