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. However, you can buy it then immediately sell it on the same day.

Find and return the maximum profit you can achieve.

```
var maxProfit = function(prices) {
const profit = prices.reduce((acc, curr, index) => {
const next = prices[index+1]
// if there isn't a next price you're already on the last day, so return the current profit
if(!next) {
return acc
}
// if the stock is higher on the next day it means you'll have a profit
if(next > curr) {
acc += next - curr
}
return acc
}, 0)
return profit
};
```

## Top comments (4)

Your implementation

fails these two examples:

codesandbox

Not the same question, this one you can buy/sell multiple times. You'll need to compare each value with the following values to get the highest profit among them all.

π Figures. Thank You!

Saved for later.

Thanks ππ»