Best Time to Buy and Sell Stock II
You're given an integer array prices, where prices[i] is the stock's price on day i. You're free to buy and sell as many times as you like, on any days, but you can never hold more than one share at once (so you must sell before buying again). Determine the maximum total profit obtainable.
Input Format
Implement maxProfit(prices). Inputs below show JavaScript function arguments; there is no stdin parsing.
Output Format
Return the result described in the statement.
Sample Input and Output
Example 1 ยท Run Sample
Input
prices = [7,1,5,3,6,4] Output
7 Example 2
Input
prices = [7,6,4,3,1] Output
0 Constraints
- 1 <= prices.length <= 3 * 10^4
- 0 <= prices[i] <= 10^4
Test Cases (2)
Case 1
Args: [[7,1,5,3,6,4]]
Expected: 7
Case 2
Args: [[7,6,4,3,1]]
Expected: 0
Topics
Iterate through prices and add every positive difference between consecutive days to the total profit. This captures every upward movement.
function maxProfit(prices) {
let profit = 0;
for (let i = 1; i < prices.length; i++) {
if (prices[i] > prices[i - 1]) {
profit += prices[i] - prices[i - 1];
}
}
return profit;
}Time: O(n) Space: O(1)
Saved in this browser only. Private to you.