-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaxCircularSubArray.java
More file actions
75 lines (60 loc) · 2.37 KB
/
maxCircularSubArray.java
File metadata and controls
75 lines (60 loc) · 2.37 KB
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
67
68
69
70
71
72
73
74
75
import java.util.*;
public class maxCircularSubArray {
public static int kadane(int[] A) {
// stores the sum of maximum subarray found so far
int max_so_far = 0;
// stores the maximum sum of subarray ending at the current position
int max_ending_here = 0;
// traverse the given array
for (int value : A) {
// update the maximum sum of subarray "ending" at index `i` (by adding the
// current element to maximum sum ending at previous index `i-1`)
max_ending_here = max_ending_here + value;
// if the maximum sum is negative, set it to 0 (which represents
// an empty subarray)
max_ending_here = Integer.max(max_ending_here, 0);
// update result if the current subarray sum is found to be greater
max_so_far = Integer.max(max_so_far, max_ending_here);
}
return max_so_far;
}
// Function to find the maximum sum circular subarray in a given array
public static int runCircularKadane(int[] A) {
// empty array has sum of 0
if (A.length == 0) {
return 0;
}
// find the maximum element present in a given array
int max = Arrays.stream(A).max().getAsInt();
// if the array contains all negative values, return the maximum element
if (max < 0) {
return max;
}
// negate all the array elements
Arrays.setAll(A, i -> -A[i]);
// run Kadane’s algorithm on the modified array
int neg_max_sum = kadane(A);
// restore the array
Arrays.setAll(A, i -> -A[i]);
/*
* Return the maximum of the following: 1. Sum returned by Kadane’s algorithm on
* the original array. 2. Sum returned by Kadane’s algorithm on the modified
* array + the sum of all the array elements.
*/
return Integer.max(kadane(A), Arrays.stream(A).sum() + neg_max_sum);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t > 0) {
t--;
int n = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
System.out.println(runCircularKadane(a));
}
sc.close();
}
}