Best Time to Buy and Sell Stock II
You are given an integer array prices where prices[i] is the price of a given stock on the ith day. On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. Find and return the maximum profit you can achieve.
Sample Input
prices = [7,1,5,3,6,4]
Sample Output
7
Constraints
- 1 <= prices.length <= 3 * 10^4
- 0 <= prices[i] <= 10^4
Test Cases
Case 1
Args: [[7,1,5,3,6,4]]
Expected: 7
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.