918. Maximum Sum Circular Subarray [JavaScript]

探讨了在环形数组中寻找最大子数组和的问题,采用动态规划算法,考虑到数组首尾相连的特点,提供了一种高效求解策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、题目

Given a circular array C of integers represented by A, find the maximum possible sum of a non-empty subarray of C.

Here, a circular array means the end of the array connects to the beginning of the array. (Formally, C[i] = A[i] when 0 <= i < A.length, and C[i+A.length] = C[i] when i >= 0.)

Also, a subarray may only include each element of the fixed buffer A at most once. (Formally, for a subarray C[i], C[i+1], …, C[j], there does not exist i <= k1, k2 <= j with k1 % A.length = k2 % A.length.)

二、题目大意

数组A是一个环形数组,求解最大子数组的和,并且子数组必须有一个元素。

三、解题思路

这道题和求最大子串的题目有点类似,通过动态规划可以轻松的求出最大子串的和,但是这里的最大值可能存在于 A[0 - i] + A[j - max]:

四、代码实现
const maxSubarraySumCircular = (A) => {
  let total = A[0]
  let dpmax = A[0]
  let dpmin = A[0]

  let max = A[0]
  let min = A[0]

  for (let i = 1; i < A.length; i++) {
    const item = A[i]
    total += item
    dpmax = Math.max(item, dpmax + item)
    dpmin = Math.min(item, dpmin + item)

    max = Math.max(dpmax, max)
    min = Math.min(dpmin, min)
  }
  return max > 0 ? Math.max(max, total - min) : max
}

  如果本文对您有帮助,欢迎关注微信公众号,为您推送更多大前端相关的内容, 欢迎留言讨论,ε=ε=ε=┏(゜ロ゜;)┛。

  您还可以在这些地方找到我:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值