题解 | #环形数组的连续子数组最大和#

环形数组的连续子数组最大和

https://www.nowcoder.com/practice/e9f3282363844355aa51497c5410beee

/**
 * 动态规划,计算出非环形数组各项的最大值
 * 环形数据最大和子集考虑两种情况
 *      该子集横跨与不横跨
 *      横跨时,反向求解总和减去最小值
 * 
 * @param nums int整型一维数组 
 * @return int整型
 */
export function maxSubarraySumCircular(nums: number[]): number {
    const maxList = Array(nums.length).fill(0);
    const minList = Array(nums.length).fill(0);
    let sum = 0;
    nums.forEach(( item,index )=>{
        sum+=item;
        if((maxList[index -1] || 0 ) < 0){
            maxList[index] = nums[index]
        } else{
            maxList[index] = (maxList[index - 1] || 0) + nums[index];
        }
        if((minList[index -1] || 0 ) > 0){
            minList[index] = nums[index]
        } else{
            minList[index] = (minList[index - 1] || 0) + nums[index];
        }
    })
   if(sum === Math.min(...minList)){
    return Math.max(...maxList)
   }
    const max= sum - Math.min(...minList)
    return Math.max(max, ...maxList)
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务