JAVA implements the maximum in the loop array, the sum of consecutive sub-arrays

There is a similar topic on the Swordsman Offer:

--------------> What is the maximum sum of consecutive subarrays of an array ?

--------------> What is the maximum sum of consecutive subarrays of the loop array ?

The array is easy to say that the sum of the node before the judgment is < 0; there is no need to take the number to repay the debt, directly set sum=a[i]; loop in turn 

[Key point max should be initialized to Integer.MIN_VALUE at the beginning]

Looping an array: The point is that there are two possible cases for the found sum:

1.sum is composed of sub-arrays between the beginning and the end;

2.sum is composed of tail part + head part, discarding the middle part of the array. Why the middle is discarded: Because their sum is negative, and it is the smallest part of the sum.

Case 1, the same as the array method;

The point of case 2 is: find the middle part -> derivation of the array to find maxsum, which is the min part of the inverse number. Then sum the array with SUM-(-maxsum);

 
 

Maximum sum of consecutive arrays:

import java.util.Scanner;

public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int res = 0x80000000; int[] a = new int[n]; for(int i = 0;i<n;i++){ a[i] = sc.nextInt(); } int sum = 0; for(int i = 0;i<n;i++){ if(a[i]>sum && sum<0){ //这里一定要加一个sum>0 sum=a[i]; } else{ sum+=a[i]; } if(sum >res){ res=sum; } } System.out.print(res); } }


Maximum sum of contiguous subarrays of a looping array:

public class Main {
	private static  int max = Integer.MIN_VALUE;
	public static void main(String[] args) {
		int[] a={3,-1,-5,6,2};int n=a.length;
		int[]b=new int[n];int sum=0;
		//The first case, normal, the value of the maximum max array is between the beginning and the end
		int sum1=find(a,n);
		//The second case, part of the head + part of the tail; the middle part is not selected, because their sum is the smallest and negative
		//That's why I inspired the idea to find the middle part that was not selected: invert the array and find the max again
		for(int i=0;i<n;i++){
			b[i]=-a[i];
			sum+=a[i]; //sum is the sum of the array
		}
		int temp = find(b,n);
		int sum2 = sum+temp;
		max = Math.max(sum1, sum2);
		System.out.print(max);
	}
	public static int find(int[]a,int n){
		if(a==null)
			return 0;
		int sum =0;	int max1=max;
		for(int i=0;i<n;i++){		
			if(sum<=0)
				sum=a[i];
			else
				sum+=a[i];
			max1 = max1<sum?sum:max1;
		}
		return max1;
	}
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325266174&siteId=291194637