Maximum sum circular subarray GFG
package datastructure.array;
class Learning {
// Efficient siolution kadane's algorithm
public static int getMaximum(int[] arr){
int n = arr.length;
int res = arr[0];
int maxEnding = arr[0];
for(int i = 1; i < n; i++) {
maxEnding = Math.max(arr[i], maxEnding + arr[i]);
res = Math.max(res, maxEnding);
}
return res;
}
public static int overAllMaximum(int[] arr) {
int n = arr.length;
int max_Normal = getMaximum(arr);
if(max_Normal < 0){
return max_Normal;
}
int totalSum = 0;
for(int i = 0; i < n; i++) {
totalSum = totalSum + arr[i];
arr[i] = -arr[i];
}
int max_Circular = totalSum + getMaximum(arr);
return Math.max(max_Normal,max_Circular);
}
// Maximum circular subarray sum
public static int get(int[] arr) {
int n = arr.length;
int res = arr[0];
for(int i = 0; i < n; i++) {
int currentSum = arr[i];
int maxSum = arr[i];
for(int j = 1; j < n; j++) {
int index = (i + j) % n;
currentSum = arr[index] + currentSum;
maxSum = Math.max (maxSum, currentSum);
}
res = Math.max(res, maxSum);
}
return res;
}
public static void main(String[] args){
int[] array = {8,-4,3,-5,4};
System.out.println(overAllMaximum(array));
}
}
Comments
Post a Comment