您的位置:首页 > 其它

HackerRank The Maximum Subarray

2016-07-22 06:56 375 查看
原题网址:https://www.hackerrank.com/challenges/maxsubarray

Given an array  of  elements,
find the maximum possible sum of a

Contiguous subarray

Non-contiguous (not necessarily contiguous) subarray.

Empty subarrays/subsequences should not be considered.

Input Format

First line of the input has an integer .  cases
follow. 

Each test case begins with an integer .
In the next line,  integers
follow representing the elements of array .

Constraints:

The subarray and subsequences you consider
should have at least one element.

Output Format

Two, space separated, integers denoting the maximum contiguous and non-contiguous subarray. At least one integer should be selected and put into the subarrays (this may be required in cases where all elements are negative).

Sample Input

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


Sample Output

10 10
10 11


Explanation

In the first case: 

The max sum for both contiguous and non-contiguous elements is the sum of ALL the elements (as they are all positive).

In the second case: 

[2 -1 2 3 4] --> This forms the contiguous sub-array with the maximum sum. 

For the max sum of a not-necessarily-contiguous group of elements, simply add all the positive elements.

方法:动态规划。

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

public class Solution {

public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
for(int i = 0; i < t; i++) {
int n = scanner.nextInt();
int num = scanner.nextInt();
int maxContiguous = num;
int maxNonContiguous = num;
int sumContiguous = num;
sumContiguous = Math.max(sumContiguous, 0);

for(int j = 1; j < n; j++) {
num = scanner.nextInt();
maxNonContiguous = Math.max(maxNonContiguous, Math.max(maxNonContiguous + num, num));

sumContiguous += num;
maxContiguous = Math.max(maxContiguous, sumContiguous);
sumContiguous = Math.max(sumContiguous, 0);
}
System.out.println(maxContiguous + " " + maxNonContiguous);
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  hackerrank