最大子數組和(The Maximum Subarray)


問題:求一個整型數組的(1)最大連續子數組和以及(2)不要求連續的最大子數組和

要求 返回的結果不能使空數組。


解答思路:

(1)從前往後掃描數組,當前邊累加的和大於零的時候,說明這個序列對結果有益,則保留,並且加上當前數組元素A[i]。如果當前累加的和小於等於0,說明已經掃描序列會降低結果的值,有害,則拋棄,當前最大結果則爲當前元素A[i]。該算法的時間複雜度是O(n).

      但是這樣做,當所有的元素都是負數的時候,算法選擇的子數組是空的,故此時需要返回最大的負數。

(2) 只需要選擇所有的整數並相加則可以。如果這樣的結果是0,則返回最大的負數即可。


Sample Input

2 
4 
1 2 3 4
6
2 -1 2 3 4 -5

Sample Output

10 10
10 11

我的解答:


import java.io.*;
import java.util.*;

public class TheMaximumSubArray{
	public static void main(String[] args){
		Scanner scan = new Scanner(System.in);
		int T = scan.nextInt();
		scan.nextLine();
		for(int i = 0; i < T; i ++){
			int N = scan.nextInt();
			
			// input a array of data
			int[] numbers = new int[N];
			for(int j = 0; j < N; j++){
				// System.out.print(j);
				numbers[j] = scan.nextInt();
			}

			// DP
			// 1. Contiguous subarray
			int maxResult = 0;
			int result1 = 0; //temp
			int maxResultNagtive = Integer.MIN_VALUE;
			for(int k = 0; k < N; k ++){
				if(result1 < 0){
					result1 = numbers[k];
				}
				else{
					result1 += numbers[k];
				}
				if(result1 > maxResult){
					maxResult = result1;
				}

				// keep the smallest negative number 
				if(numbers[k] < 0 && numbers[k] > maxResultNagtive){
					maxResultNagtive = numbers[k];
				}
			}
			// if no positive result found, return the 
			if(maxResult == 0){
				maxResult = maxResultNagtive;
			}	


			//2. Not necessarily contiguous
			int maxResult2 = 0;
			int maxResultNagtive2 = Integer.MIN_VALUE;
			for(int m = 0; m < N; m ++){
				if(numbers[m] > 0){
					maxResult2 += numbers[m];
				}

				if(numbers[m] < 0 && numbers[m] > maxResultNagtive2){
					maxResultNagtive2 = numbers[m];
				}
			}
			if(maxResult2 == 0){
				maxResult2 = maxResultNagtive2;
			}

			// output
			System.out.print(maxResult); 
			System.out.print(" ");
			System.out.println(maxResult2);
			// System.out.println(Arrays.toString(numbers));
			// scan.nextLine();
		}
		scan.close();
	}
}



發佈了40 篇原創文章 · 獲贊 6 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章