Maximum-Subarray - DSA Question 3
DSA by Apna college

Sure, let's break down the "Maximum Subarray" problem in detail and provide a simple explanation along with Java code.
Problem Statement:
Given an integer array nums, find the contiguous subarray (containing at least one number) that has the largest sum and return its sum.
Approach and Explanation:
Kadane's Algorithm:
Kadane's algorithm is an efficient way to find the maximum subarray sum. It works by iterating through the array and keeping track of the maximum subarray ending at the current position. If the sum becomes negative, it means the current subarray is not contributing positively, so it's better to start over from the current position.
Step-by-Step Explanation:
Initialize Variables:
Initialize two variables,
maxSumandcurrentSum, to track the overall maximum sum and the current subarray sum.Set
maxSumandcurrentSumto the first element of the array (nums[0]).
Iterate Through the Array:
Start iterating from the second element (index 1) to the end of the array.
For each element, update
currentSum:If
currentSumbecomes negative, reset it to the current element. This step ensures that we are always considering a positive subarray.If
currentSumis positive, add the current element to it, extending the subarray.
Update
maxSum:- Update
maxSumwith the maximum value between the currentmaxSumandcurrentSum. This step ensures that we are always storing the maximum subarray sum encountered so far.
- Update
Continue Iterating:
- Continue the iteration until the end of the array.
Return
maxSum:- After the iteration is complete, return
maxSumas the result.
- After the iteration is complete, return
Java Code:
public class MaximumSubarray {
public int maxSubArray(int[] nums) {
int maxSum = nums[0]; // Initialize maxSum with the first element
int currentSum = nums[0]; // Initialize currentSum with the first element
// Iterate through the array starting from the second element
for (int i = 1; i < nums.length; i++) {
// If currentSum becomes negative, start a new subarray from the current element
currentSum = Math.max(nums[i], currentSum + nums[i]);
// Update maxSum with the maximum value between currentSum and maxSum
maxSum = Math.max(maxSum, currentSum);
}
return maxSum; // Return the maximum subarray sum
}
}
Explanation of the Code:
The
maxSubArrayfunction takes an integer arraynumsas input.It initializes
maxSumandcurrentSumwith the first element of the array (nums[0]).It iterates through the array, updating
currentSumbased on the conditions explained above.The
maxSumvariable keeps track of the maximum subarray sum encountered so far.After the iteration, it returns
maxSumas the result, which represents the maximum subarray sum in the given array.
This approach ensures an efficient solution to find the maximum subarray sum and is widely used in competitive programming and real-world applications where optimizing time complexity is essential.

