Skip to main content

Buy and Sell Stocks 2

Say you have an array for which the i-th 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 (i.e., buy one and sell one share of the stock multiple times).

You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

Example:

Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
  Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Write your solution:
Test Case 1
Input: [7,1,5,3,6,4]
Output: 7
Test Case 2
Input: [1,2,3,4,5]
Output: 4
Test Case 3
Input: [7,6,4,3,1]
Output: 0
Solution

Complexity:

  • Time complexity: O(n)
  • Space complexity: O(1)
function maxProfit(prices) {
let profit = 0;
prices.forEach((price, index) => {
const prevPrice = prices[index - 1];
if (price > prevPrice) {
profit += price - prevPrice;
}
});
return profit;
}