Skip to content

Commit ceda713

Browse files
committed
上升子序列最大差(dp经典)
1 parent 4ae6004 commit ceda713

File tree

2 files changed

+51
-2
lines changed

2 files changed

+51
-2
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# coding: utf8
2+
3+
4+
"""
5+
题目链接: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/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+
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock),
11+
design an algorithm to find the maximum profit.
12+
13+
Example 1:
14+
Input: [7, 1, 5, 3, 6, 4]
15+
Output: 5
16+
17+
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
18+
Example 2:
19+
Input: [7, 6, 4, 3, 1]
20+
Output: 0
21+
22+
In this case, no transaction is done, i.e. max profit = 0.
23+
24+
"""
25+
26+
27+
class Solution(object):
28+
def maxProfit(self, prices):
29+
"""
30+
:type prices: List[int]
31+
:rtype: int
32+
"""
33+
if not prices:
34+
return 0
35+
36+
return self.dynamic_max_profit(prices)
37+
38+
# 动态规划
39+
# 搜索局部上升子序列, 保存当前最优解
40+
def dynamic_max_profit(self, prices):
41+
start = 0
42+
ans = 0
43+
for i in range(1, len(prices)):
44+
delta = prices[i] - prices[start]
45+
if delta > 0:
46+
ans = max(ans, delta)
47+
else:
48+
start = i
49+
50+
return ans

DynamicProgramming/53_MaximumSubarray.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,7 @@ def dynamic_sub_array(self, nums):
3636
cur = 0
3737
for i in range(len(nums)):
3838
cur += nums[i]
39-
if cur > ans:
40-
ans = cur
39+
ans = max(ans, cur)
4140
if cur < 0:
4241
cur = 0
4342

0 commit comments

Comments
 (0)