Skip to content

Commit 9528b0d

Browse files
Create BestTimeToBuyAndSellStock2.js
1 parent 55ff0ad commit 9528b0d

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// Link :- https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
2+
/*
3+
* You are given an integer array prices where prices[i] is the price of a given stock on the ith day.
4+
* 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.
5+
* Find and return the maximum profit you can achieve.
6+
*/
7+
8+
/**
9+
* @param {number[]} prices
10+
* @return {number}
11+
*/
12+
var maxProfit = function(prices) {
13+
const n = prices.length;
14+
const dp = Array.from({ length: n }, () => Array(2).fill(0));
15+
16+
for (let i = n - 1; i >= 0; i--) {
17+
if (i === n - 1) {
18+
dp[i][0] = 0;
19+
dp[i][1] = prices[i];
20+
continue;
21+
}
22+
dp[i][0] = Math.max(dp[i + 1][1] - prices[i], dp[i + 1][0]);
23+
dp[i][1] = Math.max(dp[i + 1][1], dp[i + 1][0] + prices[i]);
24+
}
25+
26+
return dp[0][0];
27+
};

0 commit comments

Comments
 (0)