122. Best Time to Buy and Sell Stock II

Description

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

/**
 * Solved with two pointers
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    "use strict";
    let profit = 0;
    // Use pointer j to find ascending sequences and another pointer i for pointing the current lowest price
    for (let i = 0, j = 0; j < prices.length; j++) {
        if (prices[j] < prices[j-1]) {
            profit += (prices[j-1]-prices[i]);
            i = j;
        }
        // If the end of sequence is also ascending then make final transaction
        if (j === prices.length-1 && i !== j) {
            profit += (prices[j]-prices[i]);
        }
    }
    return profit;
};

results matching ""

    No results matching ""