Lincode42.最大子数组 II-----前缀和

题目表述

描述
给定一个整数数组,找出两个 不重叠 子数组使得它们的和最大。
每个子数组的数字在数组中的位置应该是连续的。
返回最大的和。

示例1:
输入:nums = [1, 3, -1, 2, -1, 2]
输出:7
解释:最大的子数组为 [1, 3] 和 [2, -1, 2] 或者 [1, 3, -1, 2] 和 [2].

双数组

public class Solution { /** * @param nums: A list of integers * @return: An integer denotes the sum of max two non-overlapping subarrays */ public int maxTwoSubArrays(List<Integer> nums) { // write your code here int[] leftSeqMax = new int[nums.size()]; int[] rightSeqMax = new int[nums.size()]; int max_mum = Integer.MIN_VALUE; int cur = 0; for(int i = 0; i < nums.size(); i++){ if(cur <= 0){ cur = nums.get(i); }else{ cur += nums.get(i); } leftSeqMax[i] = max_mum = Math.max(max_mum, cur); } max_mum = Integer.MIN_VALUE; cur = 0; for(int i = nums.size() - 1; i >= 0; i--){ if(cur <= 0){ cur = nums.get(i); }else{ cur += nums.get(i); } rightSeqMax[i] = max_mum = Math.max(max_mum, cur); } int res = Integer.MIN_VALUE; for(int i =0; i < nums.size() - 1;i++){ res = Math.max(res, leftSeqMax[i] + rightSeqMax[i + 1]); } return res; } }

__EOF__

本文作者Younger
本文链接https://www.cnblogs.com/youngerwb/p/16450652.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   YoungerWb  阅读(62)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示