Update 0053.最大子序和.md

This commit is contained in:
jianghongcheng
2023-05-31 23:44:40 -05:00
committed by GitHub
parent 18a406e14f
commit d988722396

View File

@ -198,21 +198,35 @@ class Solution {
```
### Python
暴力法
```python
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
result = -float('inf')
def maxSubArray(self, nums):
result = float('-inf') # 初始化结果为负无穷大
count = 0
for i in range(len(nums)): # 设置起始位置
count = 0
for j in range(i, len(nums)): # 从起始位置i开始遍历寻找最大值
count += nums[j]
result = max(count, result) # 更新最大值
return result
```
```python
class Solution:
def maxSubArray(self, nums):
result = float('-inf') # 初始化结果为负无穷大
count = 0
for i in range(len(nums)):
count += nums[i]
if count > result:
if count > result: # 取区间累计的最大值(相当于不断确定最大子序终止位置)
result = count
if count <= 0:
if count <= 0: # 相当于重置最大子序起始位置,因为遇到负数一定是拉低总和
count = 0
return result
```
```
### Go
```go