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

Solution: Peak Valley Approach

The key point is we need to consider every peak immediately following a valley to maximize the profit. In case we skip one of the peaks (trying to obtain more profit), we will end up losing the profit over one of the transactions leading to an overall lesser profit.

int maxProfit(vector<int>& prices) {
    if(prices.size() <= 1) return 0;

    int i = 0;
    int valley = prices[0];
    int peak = prices[0];
    int maxProfit = 0;

    while(i < prices.size()-1) {
        while (i < prices.size() - 1 && prices[i] >= prices[i + 1]) {
            i += 1;
        }
        valley = prices[i];

        while (i < prices.size() - 1 && prices[i] <= prices[i + 1]) {
            i += 1;
        }
        peak = prices[i];

        maxProfit = += peak - valley;
    }
    return maxProfit;
}

Solution: Simple one pass

Instead of looking for every peak following a valley, we can simply go on crawling over the slope and keep on adding the profit obtained from every consecutive transaction.

Note: If we don't need to track the days of the transaction

int maxProfit(vector<int>& prices) {
    if(prices.size() <= 1) return 0;

    int profit = 0;
    for(int i=0; i < prices.size()-1; i++) {
        if(prices[i+1] > prices[i]) {
            profit += prices[i+1] - prices[i];
        }
    }

    return profit;
}

results matching ""

    No results matching ""