# LeetCode 122. Best Time to Buy and Sell Stock II (javascript)

### Description:

You are given an array prices where prices[i] is the price of a given stock on the ith day.

Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).

Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

### Solution:

Time Complexity : O(n)
Space Complexity: O(1)

`````` var maxProfit = function(prices) {
let maxprofit = 0;
for (let i = 1; i < prices.length; i++) {
// Add to the max profit total if the current price is greater than previous
// We "sell" when the the opposite is true because we will not buy on days that dip.
if (prices[i] > prices[i - 1])
// Add the increse in price to our profit
maxprofit += prices[i] - prices[i - 1];
}
return maxprofit;
};
`````` A working solution from the one non-working above (JAVASCRIPT):

``````const maxPorfit = (prices) => {
let maxProfit = 0
minPrice= prices
for(let sell = 1; sell < prices.length; sell++) {
let sellPrice = prices[sell]
profit = sellPrice - minPrice

maxProfit = Math.max(maxProfit, profit)
if(sellPrice < minPrice) minPrice = sellPrice
}
return maxProfit
}
`````` NOTE: on line 3 and line 6 I didn't write "let" to declare a variable, because I declared one prior to it so I didn't need to use "let" again, but for clarification you can use the "let" keyword and it will work the same. kao

Original post is valid I have tested it.