122. Best Time to Buy and Sell Stock II
My accepted JavaScript solution to LeetCode problem 122, Best Time to Buy and Sell Stock II, running in 1ms.
- Difficulty: Medium
- JavaScript
- Runtime 1ms
- Memory 54.6MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
JavaScript
Accepted on LeetCode — runtime 1ms, memory 54.6MB, accepted 2025-12-24.
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
// Greedy: capture every upward slope
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;
};