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).

public class Solution {
    public int maxProfit(int[] prices) {
        int maxProfit = 0;
        int buyDay = -1; //keep track of the index of last buyDay
        int runner = 0;
        while (runner < prices.length-1) {
            if (runner + 1 < prices.length) {
                if (buyDay == -1 && prices[runner + 1] > prices[runner]) {
                    buyDay = runner;
                }
                if (buyDay != -1 && prices[runner + 1] < prices[runner]) {
                    maxProfit += prices[runner] - prices[buyDay];
                    buyDay = -1;
                }
            }
            runner++;
        }
        if (buyDay != -1 && prices[runner] > prices[buyDay]) {
            maxProfit += prices[runner] - prices[buyDay];
        }
        return maxProfit;
    }
}

Note:
Use a runner starting from the beginning of the array. Also need a variable called buyDay to keep track of the last buy day. -1 means there is no buy order yet or a sell order has just been placed, aka, next step is to buy. if buyDay equals to other integers, means next step is to sell.

When to Buy:
If next step is to buy and the price is increasing(means the price of next day is higher than the price of current day).

When to Sell:
If next step is to sell and the price is decreasing. the profit should be calculated and added to the maxProfit when sell order is placed.
Remember to check the edge cases, when it is the last day, there is no way to check if the price is increasing or decreasing. So just check if it has higher price than the buyDay.

Time Complexity:
O(n) only need to go through the array once.

FacebookTwitterGoogle+Share

Leave a Reply

Your email address will not be published. Required fields are marked *