From d9887223965e84771503808e5685c1307998fabe Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Wed, 31 May 2023 23:44:40 -0500 Subject: [PATCH] =?UTF-8?q?Update=200053.=E6=9C=80=E5=A4=A7=E5=AD=90?= =?UTF-8?q?=E5=BA=8F=E5=92=8C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0053.最大子序和.md | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/problems/0053.最大子序和.md b/problems/0053.最大子序和.md index 48f8be29..bc5e1d55 100644 --- a/problems/0053.最大子序和.md +++ b/problems/0053.最大子序和.md @@ -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