forked from akshitagit/JAVA
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Maximum circular subarray sum Issue akshitagit#65, tested OK
- Loading branch information
Showing
1 changed file
with
42 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
package hacktober; | ||
|
||
import java.util.Arrays; | ||
import java.util.Scanner; | ||
|
||
public class Max_sum_circular_array { | ||
|
||
public static void main(String[] args) { | ||
// TODO Auto-generated method stub | ||
Scanner sc = new Scanner(System.in); | ||
System.out.println("Enter number of element to be in array"); | ||
int n = sc.nextInt(); | ||
int[] arr = new int[n]; | ||
System.out.println("Enter elements to the array"); | ||
for (int i = 0; i < n; i++) { | ||
arr[i] = sc.nextInt(); | ||
} | ||
|
||
System.out.println(maxSumCircular(arr)); | ||
} | ||
private static int maxSumCircular(int[] A) { | ||
// TODO Auto-generated method stub | ||
int curMax = 0; | ||
int max = Integer.MIN_VALUE; | ||
int curMin = 0; | ||
int min = Integer.MAX_VALUE; | ||
int sum = 0; | ||
for (int i : A) { | ||
sum += i; | ||
curMin = Math.min(curMin + i, i); | ||
min = Math.min(curMin, min); | ||
curMax = Math.max(curMax + i, i); | ||
max = Math.max(curMax, max); | ||
} | ||
if (sum == min) { | ||
return max; | ||
} | ||
return Math.max(max, sum - min); | ||
|
||
} | ||
|
||
} |