用 Python 编写程序来查找任意子数组的最大绝对和

pythonserver side programmingprogramming更新于 2025/11/30 18:20:17

假设我们有一个名为 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:= nums 的大小

  • ans:= 0, temp:= 0

  • 对于范围为 0 到 n - 1 的 i,执行

    • 如果 temp < 0,则

      • temp:= 0

    • temp:= temp + nums[i]

    • ans:= ans 和 |temp| 的最大值

  • temp:= 0

  • 对于 0 到 n - 1 范围内的 i,执行

    • 如果 temp > 0,则

      • temp:= 0

    • temp:= temp + nums[i]

    • ans:= 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

相关文章


有用资源