Skip to content

Commit 1c1b244

Browse files
committedDec 23, 2020
Add dynamic programming version.
1 parent 79cf9eb commit 1c1b244

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import dpBestTimeToBuySellStocks from '../dpBestTimeToBuySellStocks';
2+
3+
describe('dpBestTimeToBuySellStocks', () => {
4+
it('should find the best time to buy and sell stocks', () => {
5+
let visit;
6+
7+
expect(dpBestTimeToBuySellStocks([1, 5])).toEqual(4);
8+
9+
visit = jest.fn();
10+
expect(dpBestTimeToBuySellStocks([1], visit)).toEqual(0);
11+
expect(visit).toHaveBeenCalledTimes(1);
12+
13+
visit = jest.fn();
14+
expect(dpBestTimeToBuySellStocks([1, 5], visit)).toEqual(4);
15+
expect(visit).toHaveBeenCalledTimes(2);
16+
17+
visit = jest.fn();
18+
expect(dpBestTimeToBuySellStocks([5, 1], visit)).toEqual(0);
19+
expect(visit).toHaveBeenCalledTimes(2);
20+
21+
visit = jest.fn();
22+
expect(dpBestTimeToBuySellStocks([1, 5, 10], visit)).toEqual(9);
23+
expect(visit).toHaveBeenCalledTimes(3);
24+
25+
visit = jest.fn();
26+
expect(dpBestTimeToBuySellStocks([10, 1, 5, 20, 15, 21], visit)).toEqual(25);
27+
expect(visit).toHaveBeenCalledTimes(6);
28+
29+
visit = jest.fn();
30+
expect(dpBestTimeToBuySellStocks([7, 1, 5, 3, 6, 4], visit)).toEqual(7);
31+
expect(visit).toHaveBeenCalledTimes(6);
32+
33+
visit = jest.fn();
34+
expect(dpBestTimeToBuySellStocks([1, 2, 3, 4, 5], visit)).toEqual(4);
35+
expect(visit).toHaveBeenCalledTimes(5);
36+
37+
visit = jest.fn();
38+
expect(dpBestTimeToBuySellStocks([7, 6, 4, 3, 1], visit)).toEqual(0);
39+
expect(visit).toHaveBeenCalledTimes(5);
40+
41+
visit = jest.fn();
42+
expect(dpBestTimeToBuySellStocks(
43+
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
44+
visit,
45+
)).toEqual(19);
46+
expect(visit).toHaveBeenCalledTimes(20);
47+
});
48+
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* Finds the maximum profit from selling and buying the stocks.
3+
* DYNAMIC PROGRAMMING APPROACH.
4+
*
5+
* @param {number[]} prices - Array of stock prices, i.e. [7, 6, 4, 3, 1]
6+
* @param {function(): void} visit - Visiting callback to calculate the number of iterations.
7+
* @return {number} - The maximum profit
8+
*/
9+
const dpBestTimeToBuySellStocks = (prices, visit = () => {}) => {
10+
visit();
11+
let lastBuy = -prices[0];
12+
let lastSold = 0;
13+
14+
for (let day = 1; day < prices.length; day += 1) {
15+
visit();
16+
const curBuy = Math.max(lastBuy, lastSold - prices[day]);
17+
const curSold = Math.max(lastSold, lastBuy + prices[day]);
18+
lastBuy = curBuy;
19+
lastSold = curSold;
20+
}
21+
22+
return lastSold;
23+
};
24+
25+
export default dpBestTimeToBuySellStocks;

0 commit comments

Comments
 (0)
Please sign in to comment.