Skip to content

Commit 3a04ad1

Browse files
add: 接雨水和买卖股票
1 parent 0280c02 commit 3a04ad1

File tree

2 files changed

+59
-12
lines changed

2 files changed

+59
-12
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
function maxProfit(prices) {
2+
const len = prices.length;
3+
// 创建dp数组
4+
const dp = new Array(len).fill([0, 0]);
5+
// dp数组初始化
6+
dp[0] = [-prices[0], 0];
7+
for (let i = 1; i < len; i++) {
8+
// 更新dp[i]
9+
dp[i] = [
10+
Math.max(dp[i - 1][0], -prices[i]),
11+
Math.max(dp[i - 1][1], prices[i] + dp[i - 1][0]),
12+
];
13+
}
14+
return dp[len - 1][1];
15+
}
16+
17+
console.log(maxProfit([7,1,5,3,6,4])) // 5
18+
19+
20+
21+
22+
23+
24+
25+
26+
27+
28+
29+
30+
31+
32+
33+
34+
35+
36+
37+
// 解法一:贪心
38+
// let res = 0, low = Infinity
39+
// for (let i = 0; i < prices.length; i++) {
40+
// low = Math.min(low, prices[i])
41+
// res = Math.max(res, prices[i] - low)
42+
// }
43+
// return res
44+
45+
46+
// 解法二:动态规划

src/arr/接雨水.ts

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,25 @@
11
// 给定[0,1,0,2,1,0,1,3,2,1,2,1]
22

33
function rain(height) {
4-
let left = 0, right = height.length - 1;
5-
let leftMax = 0, rightMax = 0, res = 0;
6-
while(left < right) {
7-
leftMax = Math.max(leftMax, height[left])
8-
rightMax = Math.max(rightMax, height[right])
9-
if(height[left] < height[right]) {
10-
res += leftMax - height[left]
11-
left++
4+
let leftIndex = 0, rightIndex = height.length - 1;
5+
let leftMax = 0, rightMax = 0;
6+
let res = 0
7+
while(leftIndex < rightIndex) {
8+
leftMax = Math.max(leftMax, height[leftIndex])
9+
rightMax = Math.max(rightMax, height[rightIndex])
10+
if(height[leftIndex] < height[rightIndex]) {
11+
res += leftMax - height[leftIndex]
12+
leftIndex++
1213
}else {
13-
res += rightMax - height[right]
14-
right--
14+
res += rightMax - height[rightIndex]
15+
rightIndex--
1516
}
1617
}
1718
return res
1819
}
1920

2021

21-
22+
console.log(rain([0,1,0,2,1,0,1,3,2,1,2,1])) // 6
2223

2324

2425

@@ -59,4 +60,4 @@ function rain(height) {
5960
// return res
6061
// }
6162

62-
console.log(rain([0,1,0,2,1,0,1,3,2,1,2,1]))
63+
// console.log(rain([0,1,0,2,1,0,1,3,2,1,2,1]))

0 commit comments

Comments
 (0)