mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 07:35:35 +08:00
Update 0053.最大子序和.md
This commit is contained in:
@ -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
|
||||
|
Reference in New Issue
Block a user