MCPcopy Create free account
hub / github.com/apna-college/Alpha / MaxSubarraySum

Class MaxSubarraySum

1_Arrays/MaxSubarraySum.java:4–63  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

2package Arrays;
3
4public class MaxSubarraySum {
5 //bruteforce
6 public static void maxSubarraySum1(int arr[]) {
7 int largestSum = Integer.MIN_VALUE;
8
9 for(int i=0; i<arr.length; i++) {
10 for(int j=i+1; j<arr.length; j++) {
11 int currSum = 0;
12 for(int k=i; k<=j; k++) {
13 currSum += arr[k];
14 }
15 largestSum = Math.max(largestSum, currSum);
16 }
17 }
18
19 System.out.println("max subarray sum is : " + largestSum);
20 }
21
22 //optimization1 : Prefix Sum array
23 public static void maxSubarraySum2(int arr[]) {
24 int maxSum = Integer.MIN_VALUE;
25
26 int prefix[] = new int[arr.length];
27 prefix[0] = arr[0];
28 for(int i=1; i<arr.length; i++) {
29 prefix[i] = prefix[i-1] + arr[i];
30 }
31
32 for(int i=0; i<arr.length; i++) {
33 for(int j=i+1; j<arr.length; j++) {
34 int currSum = i==0 ? prefix[j] : prefix[j] - prefix[i-1];
35 maxSum = Math.max(maxSum, currSum);
36 }
37 }
38
39 System.out.println("max subarray sum is : " + maxSum);
40 }
41
42 //Kadane's Algorithm
43 public static void maxSubarraySum3(int arr[]) {
44 int cs = 0;
45 int ms = 0;
46
47 for(int i=0; i<arr.length; i++) {
48 cs = cs + arr[i];
49 if(cs < 0) {
50 cs = 0;
51 }
52 ms = Math.max(ms, cs);
53 }
54
55 System.out.println("max subarray sum is : " + ms);
56 }
57 public static void main(String args[]) {
58 int arr[] = {1, -2, 6, -1, 3};
59 maxSubarraySum1(arr);
60 maxSubarraySum2(arr);
61 maxSubarraySum3(arr);

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…