访问量: 10 次浏览
假设我们有一个名为 nums 的数组。我们需要找到子数组 nums[l], nums[l+1], ..., nums[r-1], nums[r] 的最大绝对和 |nums[l] + nums[l+1] + ... + nums[r-1] + nums[r]|。
我们需要返回 nums 的任何子数组的最大绝对和(子数组可能为空)。
因此,如果输入为 nums = [2, -4, -3, 2, -6],则输出为 11,因为子数组 [2, -4, -3, 2] 具有最大的绝对子数组和 |2 + (-4) + (-3) + 2| = 11。
为了解决这个问题,我们将按照以下步骤进行 –
n := len(nums)ans := 0, temp := 0对于 i 在范围 0 到 n-1 之间,执行以下操作
如果 temp < 0,则
temp := 0temp := temp + nums[i]ans := max(ans, |temp|)temp := 0对于 i 在范围 0 到 n-1 之间,执行以下操作
如果 temp > 0,则
temp := 0temp := temp + nums[i]ans := max(ans, |temp|)ans让我们看一下以下实现以获得更好的理解-
def solve(nums):
n = len(nums)
ans = 0
temp = 0
for i in range(n):
if (temp < 0):
temp = 0
temp = temp + nums[i]
ans = max(ans, abs(temp))
temp = 0
for i in range(n):
if (temp > 0):
temp = 0
temp = temp + nums[i]
ans = max(ans, abs(temp))
return ans
nums = [2,-4,-3,2,-6]
print(solve(nums))
[2,-4,-3,2,-6]
11