The Maximum Subarray Sum problem is about finding the maximum sum of a contiguous subarray within an array of integers. In simple terms, we need to identify the largest sum we can obtain by adding consecutive elements from the array.
Kadane’s Algorithm is an efficient approach to solve this problem. The algorithm uses a clever technique to keep track of the maximum subarray sum as it iterates through the array. At each step, it decides whether to include the current element in the sum or start a new subarray from that element.
Step-by-Step Approach:
- Initialize two variables,
maxSoFarandmaxEndingHere, to store the maximum sum encountered so far and the maximum sum ending at the current index, respectively. Set both variables to the first element of the array. - Iterate through the array from the second element:
- Calculate the new
maxEndingHereby taking the maximum of the current element or adding the current element to the previousmaxEndingHere. - Update
maxSoFarby taking the maximum of the currentmaxSoFarand the newmaxEndingHere.
- After the iteration, the variable
maxSoFarwill contain the maximum subarray sum.
Java Solution:
public class MaximumSubarraySum {
public static int maxSubArraySum(int[] nums) {
int maxSoFar = nums[0];
int maxEndingHere = nums[0];
for (int i = 1; i < nums.length; i++) {
maxEndingHere = Math.max(nums[i], maxEndingHere + nums[i]);
maxSoFar = Math.max(maxSoFar, maxEndingHere);
}
return maxSoFar;
}
public static void main(String[] args) {
int[] nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
System.out.println("Maximum Subarray Sum: " + maxSubArraySum(nums));
}
}
Python Solution:
def max_subarray_sum(nums):
max_so_far = max_ending_here = nums[0]
for num in nums[1:]:
max_ending_here = max(num, max_ending_here + num)
max_so_far = max(max_so_far, max_ending_here)
return max_so_far
if __name__ == "__main__":
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
print("Maximum Subarray Sum:", max_subarray_sum(nums))
Explanation of Java/Python Solution:
The Java and Python solutions both implement Kadane’s Algorithm to find the maximum subarray sum. The maxSubArraySum function in Java and max_subarray_sum function in Python accept an array nums as input and return the maximum subarray sum.
The solution iterates through the array, updating maxEndingHere at each step to include the current element if it results in a larger subarray sum. The maxSoFar variable stores the maximum sum encountered during the iteration, which represents the answer to the problem.
The provided example array [-2, 1, -3, 4, -1, 2, 1, -5, 4] demonstrates how Kadane’s Algorithm efficiently finds the maximum subarray sum. The expected output for this example is 6, which corresponds to the subarray [4, -1, 2, 1] with the sum of 6.