mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Merge pull request #1749 from roylx/master
Update 0376.摆动序列.md 增加python优化动态规划版 Update 0121.买卖股票的最佳时机.md 增加Python动态规划版本三 Update 0714.买卖股票的最佳时机含手续费 更新Python贪心,更容易理解 Update 0055.跳跃游戏.md 增加python for循环版
This commit is contained in:
@ -119,6 +119,19 @@ class Solution:
|
||||
return False
|
||||
```
|
||||
|
||||
```python
|
||||
## for循环
|
||||
class Solution:
|
||||
def canJump(self, nums: List[int]) -> bool:
|
||||
cover = 0
|
||||
if len(nums) == 1: return True
|
||||
for i in range(len(nums)):
|
||||
if i <= cover:
|
||||
cover = max(i + nums[i], cover)
|
||||
if cover >= len(nums) - 1: return True
|
||||
return False
|
||||
```
|
||||
|
||||
### Go
|
||||
```Go
|
||||
func canJUmp(nums []int) bool {
|
||||
|
@ -310,6 +310,18 @@ class Solution:
|
||||
return dp[(length-1) % 2][1]
|
||||
```
|
||||
|
||||
> 动态规划:版本三
|
||||
```python
|
||||
class Solution:
|
||||
def maxProfit(self, prices: List[int]) -> int:
|
||||
length = len(prices)
|
||||
dp0, dp1 = -prices[0], 0 #注意这里只维护两个常量,因为dp0的更新不受dp1的影响
|
||||
for i in range(1, length):
|
||||
dp1 = max(dp1, dp0 + prices[i])
|
||||
dp0 = max(dp0, -prices[i])
|
||||
return dp1
|
||||
```
|
||||
|
||||
Go:
|
||||
> 贪心法:
|
||||
```Go
|
||||
|
@ -264,6 +264,25 @@ class Solution:
|
||||
return max(dp[-1][0], dp[-1][1])
|
||||
```
|
||||
|
||||
```python
|
||||
class Solution:
|
||||
def wiggleMaxLength(self, nums: List[int]) -> int:
|
||||
# up i作为波峰最长的序列长度
|
||||
# down i作为波谷最长的序列长度
|
||||
n = len(nums)
|
||||
# 长度为0和1的直接返回长度
|
||||
if n<2: return n
|
||||
for i in range(1,n):
|
||||
if nums[i]>nums[i-1]:
|
||||
# nums[i] 为波峰,1. 前面是波峰,up值不变,2. 前面是波谷,down值加1
|
||||
# 目前up值取两者的较大值(其实down+1即可,可以推理前一步down和up最多相差1,所以down+1>=up)
|
||||
up = max(up, down+1)
|
||||
elif nums[i]<nums[i-1]:
|
||||
# nums[i] 为波谷,1. 前面是波峰,up+1,2. 前面是波谷,down不变,取较大值
|
||||
down = max(down, up+1)
|
||||
return max(up, down)
|
||||
```
|
||||
|
||||
### Go
|
||||
|
||||
**贪心**
|
||||
|
@ -206,13 +206,13 @@ class Solution: # 贪心思路
|
||||
result = 0
|
||||
minPrice = prices[0]
|
||||
for i in range(1, len(prices)):
|
||||
if prices[i] < minPrice:
|
||||
if prices[i] < minPrice: # 此时有更低的价格,可以买入
|
||||
minPrice = prices[i]
|
||||
elif prices[i] >= minPrice and prices[i] <= minPrice + fee:
|
||||
continue
|
||||
else:
|
||||
result += prices[i] - minPrice - fee
|
||||
elif prices[i] > (minPrice + fee): # 此时有利润,同时假买入高价的股票,看看是否继续盈利
|
||||
result += prices[i] - (minPrice + fee)
|
||||
minPrice = prices[i] - fee
|
||||
else: # minPrice<= prices[i] <= minPrice + fee, 价格处于minPrice和minPrice+fee之间,不做操作
|
||||
continue
|
||||
return result
|
||||
```
|
||||
|
||||
|
Reference in New Issue
Block a user