Skip to content

Commit 362a130

Browse files
committed
update: DP method
1 parent b29e9a6 commit 362a130

File tree

1 file changed

+18
-1
lines changed
  • src/best-time-to-buy-and-sell-stock

1 file changed

+18
-1
lines changed

‎src/best-time-to-buy-and-sell-stock/res.js

+18-1
Original file line numberDiff line numberDiff line change
@@ -22,4 +22,21 @@ var maxProfit = function(prices) {
2222
}
2323

2424
return res;
25-
};
25+
};
26+
27+
/**
28+
* DP 解法
29+
* @param {*} prices
30+
*/
31+
var maxProfit_2 = (prices) => {
32+
if (prices.length < 2) return 0;
33+
34+
let last = 0, max = 0;
35+
36+
for (let i = 1; i < prices.length; i++) {
37+
last = Math.max(0, last + prices[i] - prices[i-1]);
38+
max = Math.max(last, max);
39+
}
40+
41+
return max;
42+
}

0 commit comments

Comments
 (0)