面试题-lintcode 42 两个不重叠子数组的最大和

题目描述:

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

注意事项:子数组最少包含一个数,要求时间复杂度为o(n).

example:

给出子数组[1,3,-1,2,-1,2],这两个子数组分别为[1,3]和[2,-1,2]或者[1,3,-1,2]和[2],它们的和都是7.返回7.

动态规划求解,思路同:https://blog.csdn.net/orangefly0214/article/details/85628042

public class maxTwoSubArrays {
	 public int maxTwoSubArr(int[] nums) {
		 int[] left=new int[nums.length];
		 int[] lMax=new int[nums.length];
		 int[] right=new int[nums.length];
		 int[] rMax=new int[nums.length];
		 left[0]=nums[0];
		 lMax[0]=nums[0];
		 //从左到右遍历,得到从以每一个索引开头的子数组的最大和
		 for(int i=1;i<nums.length;i++){
			 left[i]=Math.max(left[i-1]+nums[i],nums[i]);
			 lMax[i]=Math.max(lMax[i-1], left[i]);
		 }
		 //右往左遍历,得到以每个索引开头的子数组的最大和
		 right[nums.length-1]=nums[nums.length-1];
		 rMax[nums.length-1]=nums[nums.length-1];
		 for(int i=nums.length-2;i>=0;i--){
			 right[i]=Math.max(right[i+1]+nums[i],nums[i]);
			 rMax[i]=Math.max(right[i], rMax[i+1]);
		 }
		 //求两个子数组的最大,就是找left从0-i,right从i+1,length的最大子数组的和
		 int ret=lMax[0]+rMax[1];
		 for(int i=1;i<nums.length-1;i++){
			 if(lMax[i]+rMax[i+1]>ret){
				 ret=lMax[i]+rMax[i+1];
			 }
		 }
		return ret;
	       
	    }

	public static void main(String[] args) {
		maxTwoSubArrays msa=new maxTwoSubArrays();
		int[] arr={1,3,-1,2,-1,2};
		System.out.println(msa.maxTwoSubArr(arr));
	}
}

猜你喜欢

转载自blog.csdn.net/orangefly0214/article/details/88966899