Finding the maximum subarray sum.
Here’s an example of a Java program that finds the maximum subarray sum using the Kadane’s algorithm:
public class MaximumSubarraySum { public static int findMaximumSubarraySum(int[] nums) { int maxSoFar = nums[0]; // Initialize the maximum sum as the first element int maxEndingHere = nums[0]; // Initialize the maximum sum ending at the first element // Traverse the array starting from the second element for (int i = 1; i < nums.length; i++) { // Calculate the maximum sum ending at the current element maxEndingHere = Math.max(nums[i], maxEndingHere + nums[i]); // Update the maximum sum so far maxSoFar = Math.max(maxSoFar, maxEndingHere); } return maxSoFar; } public static void main(String[] args) { int[] nums = { -2, 1, -3, 4, -1, 2, 1, -5, 4 }; int maxSum = findMaximumSubarraySum(nums); System.out.println("Maximum subarray sum: " + maxSum); } }
In this program, the `findMaximumSubarraySum` method takes an array of integers as input and returns the maximum subarray sum. It uses two variables, `maxSoFar` and `maxEndingHere`, to keep track of the maximum sum found so far and the maximum sum ending at the current element, respectively.
The program then uses a loop to traverse the array starting from the second element. At each step, it calculates the maximum sum ending at the current element by choosing between starting a new subarray or extending the existing subarray. It updates `maxEndingHere` and `maxSoFar` accordingly.
In the `main` method, we provide an example array `nums` and call the `findMaximumSubarraySum` method to find the maximum subarray sum. Finally, the result is printed to the console.