题目链接:122. 买卖股票的最佳时机 II - 力扣(LeetCode)
思路:一开始以为自己是用动态规划的思路做的,结果看了解析才发现是用贪心的思路做的。
其实如果第0天买入,第三天卖出,那么price[3] - price[0] = (price[3] - price[2]) + (price[2] - price[1]) + (price[1] - price[0])。也就是分解成每天的利润,并且只收集正的利润。局部最优能推出全局最优,且找不出反例,就能尝试使用贪心
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
dp = [0] * len(prices)
minTemp = prices[0]
result = 0
for i in range(1, len(prices)):
get = prices[i] - minTemp
if get < 0:
minTemp = min(prices[i], minTemp)
else:
dp[i] = max(dp[i], prices[i] - minTemp)
minTemp = prices[i]
for i in range(len(dp)):
if dp[i] > 0:
result += dp[i]
return result
思路:不断更新能走到的最远距离,如果最远距离不能到达当前坐标,则返回False
class Solution(object):
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
helpEnd = nums[0] #在第一格能跳到的距离
if len(nums) == 1:
return True
for i in range(1, len(nums)):
if helpEnd < i:
return False
helpEnd = max(i + nums[i], helpEnd)
if helpEnd >= len(nums) - 1:
return True
题目链接:45. 跳跃游戏 II - 力扣(LeetCode)
思路:主要在于一直想不清楚什么时候累加步数,其实就是统计每一步所能到达的最大范围,例如[7,0,9,6,9,6,1,7,9,0,1,2,9,0,3] 第一步能走到7,那么如果7没走到终点时,下一次就要加一步,也就是遍历到下标为7的节点时,看看0 9 7 9 7 1中是否有节点能走到终点。
class Solution(object):
def jump(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1:
return 0
helpTemp = 0
nextStep = 0
result = 0
for i in range(len(nums)):
helpTemp = max(helpTemp, nums[i] + i) #更新每一步的最远距离
if i == nextStep: #到达了第一步的最远范围
result += 1
nextStep = helpTemp
if helpTemp >= len(nums) -1:
break
return result
题目链接:1005. K 次取反后最大化的数组和 - 力扣(LeetCode)
思路:先对数组进行排序,从最小负数开始依次变正,如果k还有剩余,则不断反转最小的正数
class Solution(object):
def largestSumAfterKNegations(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
# 优先把次数给最小的负数
nums.sort()
for i in range(len(nums)):
if nums[i] < 0:
nums[i] = -nums[i]
k -= 1
else:
break
if k == 0:
return sum(nums)
nums.sort()
index = 0
while k != 0:
nums[index] = -nums[index]
k = k - 1
return sum(nums)