-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTheMaximumSubarray.java
58 lines (44 loc) · 1.45 KB
/
TheMaximumSubarray.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*
Given an array A={a1,a2,...,an} of N elements, find the maximum
possible sum of a:
1. Contiguous subarray
2. Non-contiguous (not necessarily contiguous) subarray.
Empty subarrays/subsequences should not be considered.
Link: https://www.hackerrank.com/challenges/maxsubarray
*/
import java.io.*;
import java.util.*;
import java.lang.Math;
public class Solution {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numTests = input.nextInt();
for (int i = 0; i < numTests; i++) {
int arrSize = input.nextInt();
int[] arr = new int[arrSize];
for (int j = 0; j < arrSize; j++) {
arr[j] = input.nextInt();
}
System.out.println(maxContig(arr) + " " + maxNotContig(arr));
}
}
private static int maxContig(int[] arr) {
int currentMax = arr[0];
int overallMax = arr[0];
for (int i = 1; i < arr.length; i++) {
currentMax = Math.max(arr[i], currentMax + arr[i]);
overallMax = Math.max(currentMax, overallMax);
}
return overallMax;
}
private static int maxNotContig(int[] arr) {
int max = arr[0];
int sum = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] > 0) sum += arr[i];
if (arr[i] > max) max = arr[i];
}
if (sum == 0) return max;
else return sum;
}
}