python - 谁能解释这个“最大子阵列”问题?
问题描述
我曾经在网上看到这个编码问题..
给定一个整数数组 nums,找到总和最大的连续子数组(至少包含一个数)并返回它的总和。
例子:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
...并从 leetcode 用户那里得到了解决方案...
def maxSubArray(self, nums: List[int]) -> int:
sumVal = 0
ret = 0
for i in nums:
sumVal = max(0, sumVal) + i
ret = max(ret, sumVal)
return max(nums) if ret == 0 else ret
尽管即使经过一些“调试”,我也不知道它是如何工作的。
你能解释一下吗?
解决方案
正如问题所述,它的所有要求是使用连续元素(即相邻元素)在子数组中找到可能的最大值。
这里的方法是一个一个地遍历数组并将元素添加到总和中,并检查它是否超过当前最大值,如果是,则更新最大值。请参阅有关每行功能的内联注释。
def maxSubArray(self, nums: List[int]) -> int: #type hint to return an int value
sumVal = 0 #keeps the total sum
ret = 0 #return value
for i in nums: #iterates through every single value in the list
sumVal = max(0, sumVal) + i #gets the total sum for the upto the given i value
ret = max(ret, sumVal) #ret variable is updated with whichever is the max of `ret` or `sumVal`.
return max(nums) if ret == 0 else ret #retunrs max value of the array if ret = 0; this simply means array is of single element.Else return the value held in `ret`
这段代码虽然不完整。它不会尝试检查连续值,而只是检查可能的总和。
运行这个,
def maxSubArray(nums):
sumVal = 0
ret = 0
for i in nums:
sumVal = max(0, sumVal) + i
ret = max(ret, sumVal)
return max(nums) if ret == 0 else ret
print(maxSubArray([8,1,-3,4,-1,2,1,-5,4]))
给12
. 请参阅此处以了解更多信息
推荐阅读
- swift - 从 webview xcode 9 开始的应用程序
- java - 我可以使用 4096 位作为带有 OAEP 填充的 java RSA 的密钥长度吗?
- opencv - 使用 OpenCv 和 Python 在线条上分组轮廓
- python - 将“在邮政编码 X 英里内显示结果”过滤器添加到网站的最有效方法
- magento - Magento 2 错误:属性“xxx”在类中没有相应的设置器
- wordpress - 如何在 Wordpress 中打印多个类别?
- python - 创建基于文本的 RPG 库存系统 (python)
- mysql - MySQL 错误 5154:占位符无效(Node.js XDevAPI 连接器)
- ios - Swift - 滚动集合视图时标签移动到单元格的左上角
- java - 使用类对象作为类型