Skip to content

Commit 0f584e3

Browse files
committed
上升子序列求和(dp经典)
1 parent a7dfac3 commit 0f584e3

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# coding: utf8
2+
3+
4+
"""
5+
题目链接: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description.
6+
题目描述:
7+
8+
Say you have an array for which the ith element is the price of a given stock on day i.
9+
10+
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and
11+
sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time
12+
(ie, you must sell the stock before you buy again).
13+
14+
"""
15+
16+
17+
class Solution(object):
18+
def maxProfit(self, prices):
19+
"""
20+
:type prices: List[int]
21+
:rtype: int
22+
"""
23+
if not prices:
24+
return 0
25+
26+
return self.dynamic_max_profit(prices)
27+
28+
# 动态规划:
29+
# 搜索所有的上升子序列, 求和
30+
def dynamic_max_profit(self, prices):
31+
ans = 0
32+
start = 0
33+
for i in range(1, len(prices)):
34+
delta = prices[i] - prices[i - 1]
35+
if delta < 0:
36+
ans += prices[i - 1] - prices[start]
37+
start = i
38+
39+
if prices[-1] > prices[start]:
40+
ans += prices[-1] - prices[start]
41+
42+
return ans

0 commit comments

Comments
 (0)