-
Notifications
You must be signed in to change notification settings - Fork 0
/
Max circular subarray sum
66 lines (49 loc) · 1.51 KB
/
Max circular subarray sum
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
59
60
61
62
63
64
65
66
//Max circular subarray sum
import java.io.*;
import java.util.*;
class Sorting {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
for(int g = 0; g < t; g++) {
String[] str = (br.readLine()).trim().split(" ");
int arr[] = new int[str.length];
for(int i = 0; i < str.length; i++) {
arr[i] = Integer.parseInt(str[i]);
}
System.out.println(new Solution().circularSubarraySum(arr));
}
}
}
class Solution {
public int circularSubarraySum(int arr[]) {
int min = Integer.MIN_VALUE;
int max = Integer.MIN_VALUE;
int curr = 0;
for(int i = 0; i < arr.length; i++) {
curr += arr[i];
if(curr > max) {
max = curr;
}
if(curr < 0) {
curr = 0;
}
}
int totalSum = 0;
for(int i = 0; i < arr.length; i++) {
totalSum += arr[i];
}
curr = 0;
for(int i = 0; i < arr.length; i++) {
curr -= arr[i];
if(curr > min) {
min = curr;
}
if(curr < 0) {
curr = 0;
}
}
min += totalSum;
return Math.max(max, min);
}
}