Max Sum Contiguous Subarray - The Coding Shala
Home >> Interview Questions >> Max Sum Contiguous Subarray
Max Sum Contiguous Subarray InterviewBit Solution
Problem::
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example:
Given the array
[-2,1,-3,4,-1,2,1,-5,4]
,
the contiguous subarray
[4,-1,2,1]
has the largest sum = 6.
For this problem, return the maximum sum.
Solution
We can solve this problem using Kadane's Algorithm.
Java Solution::
1 2 3 4 5 6 7 8 9 10 11 12 | public class Solution { // DO NOT MODIFY THE LIST. IT IS READ ONLY public int maxSubArray(final List<Integer> A) { int curr_max = A.get(0); int max = curr_max; for(int i=1;i<A.size();i++){ curr_max = Math.max(A.get(i), curr_max+A.get(i)); max = Math.max(max, curr_max); } return max; } } |
Other Posts You May Like
Comments
Post a Comment