Matheus Costa

Posted on

# Leetcode: Best Time to Buy and Sell Stock II in JavaScript

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
};
``````

peerreynders

``````function maxProfit(prices: number[]): number {
const profit = prices.reduce<number>((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;
}
``````

fails these two examples:

``````import { sellOnce } from '../src/index';

it('Example 1:', () => {
const prices = [7, 1, 5, 3, 6, 4];
expect(sellOnce(prices)).toEqual(5);
/*
Buy on day 2 (price = 1) and sell on day 5 (price = 6)
profit = 6-1 = 5. You must buy before you sell.
*/
});

it('Example 3:', () => {
const prices = [310,315,275,295,260,270,290,230,255,250];
expect(sellOnce(prices)).toEqual(30);
/*
buy i = 4, sell i = 6
*/
});
``````
``````expect(received).toEqual(expected) // deep equality

Expected: 5

3 | it('Example 1:', () => {
4 |   const prices = [7, 1, 5, 3, 6, 4];
> 5 |   expect(sellOnce(prices)).toEqual(5);
6 |   /*
7 |   Buy on day 2 (price = 1) and sell on day 5 (price = 6)
8 |   profit = 6-1 = 5. You must buy before you sell.
Example 3:
1ms

Expected: 30

20 | it('Example 3:', () => {
21 |   const prices = [310,315,275,295,260,270,290,230,255,250];
> 22 |   expect(sellOnce(prices)).toEqual(30);
23 |   /*
24 |    buy i = 4, sell i = 6
25 |   */
``````

codesandbox

Matheus Costa

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.

peerreynders

π Figures. Thank You!

Krishna Agarwal

Saved for later.
Thanks ππ»

DEV Community

## Visualizing Promises and Async/Await π€―

βοΈ Check out this all-time classic DEV post