File tree Expand file tree Collapse file tree 2 files changed +53
-0
lines changed Expand file tree Collapse file tree 2 files changed +53
-0
lines changed Original file line number Diff line number Diff line change @@ -240,6 +240,42 @@ class Solution:
240240 res = max (res, dp[i])
241241 return res
242242```
243+
244+ 动态规划
245+
246+ ``` python
247+ class Solution :
248+ def maxSubArray (self , nums ):
249+ if not nums:
250+ return 0
251+ dp = [0 ] * len (nums) # dp[i]表示包括i之前的最大连续子序列和
252+ dp[0 ] = nums[0 ]
253+ result = dp[0 ]
254+ for i in range (1 , len (nums)):
255+ dp[i] = max (dp[i- 1 ]+ nums[i], nums[i]) # 状态转移公式
256+ if dp[i] > result:
257+ result = dp[i] # result 保存dp[i]的最大值
258+ return result
259+ ```
260+
261+ 动态规划优化
262+
263+ ``` python
264+ class Solution :
265+ def maxSubArray (self , nums : List[int ]) -> int :
266+ max_sum = float (" -inf" ) # 初始化结果为负无穷大,方便比较取最大值
267+ current_sum = 0 # 初始化当前连续和
268+
269+ for num in nums:
270+
271+ # 更新当前连续和
272+ # 如果原本的连续和加上当前数字之后没有当前数字大,说明原本的连续和是负数,那么就直接从当前数字开始重新计算连续和
273+ current_sum = max (current_sum+ num, num)
274+ max_sum = max (max_sum, current_sum) # 更新结果
275+
276+ return max_sum
277+ ```
278+
243279### Go
244280贪心法
245281``` go
Original file line number Diff line number Diff line change @@ -143,6 +143,23 @@ class Solution:
143143 return False
144144```
145145
146+ ``` python
147+ # # 基于当前最远可到达位置判断
148+ class Solution :
149+ def canJump (self , nums : List[int ]) -> bool :
150+ far = nums[0 ]
151+ for i in range (len (nums)):
152+ # 要考虑两个情况
153+ # 1. i <= far - 表示 当前位置i 可以到达
154+ # 2. i > far - 表示 当前位置i 无法到达
155+ if i > far:
156+ return False
157+ far = max (far, nums[i]+ i)
158+ # 如果循环正常结束,表示最后一个位置也可以到达,否则会在中途直接退出
159+ # 关键点在于,要想明白其实列表中的每个位置都是需要验证能否到达的
160+ return True
161+ ```
162+
146163### Go
147164
148165``` go
You can’t perform that action at this time.
0 commit comments