Skip to content

MaximumSubArraySum #2877

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions src/main/java/com/thealgorithms/others/MaximumSubArraySum.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package others;

public class MaximumSubArraySum {
//Maximum Subarray Sum using Divide and Conquer algorithm

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change


public static int MaximumSum(int[] Arr, int firstindex, int lastindex) {

if (lastindex == firstindex) {//if the first index and the last index of array are same
return Arr[ firstindex ];//it means array contains only one element
//and this element equals maximum subarray sum.
}

// Finding middle element's index of the array
int middle = ( firstindex + lastindex ) / 2;

// Finding maximum subarray sum for the left subarray

int leftMax = -1000000000;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use Integer.MIN_VALUE

int sum = 0;
for (int i = middle; i >= firstindex; i--) {
sum += Arr[ i ];//addition for sum
if (sum > leftMax) {
leftMax = sum;
}
}

// Find maximum subarray sum for the right subarray
int rightMax = -1000000000;//should be minimum value
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And here

sum = 0;
for (int i = middle + 1; i <= lastindex; i++) {
sum += Arr[ i ];//addition for sum
if (sum > rightMax) {
rightMax = sum;
}
}

// Recursive part
int maxLeftRight = Math.max (MaximumSum (Arr, firstindex, middle),//left part of the array
MaximumSum (Arr, middle + 1, lastindex));//right part of the array

// return maximum of the three
return Math.max (maxLeftRight, leftMax + rightMax);
}


}
Comment on lines +44 to +47
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
}
}
}
}