Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 362a130

Browse files
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‎

Lines changed: 18 additions & 1 deletion
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)

AltStyle によって変換されたページ (->オリジナル) /