Untitled
public class MaxSumTwoSubarrays { public static int maxSumTwoNonOverlappingSubarrays(int[] nums) { int n = nums.length; // Arrays to store max sums for left and right int[] leftMax = new int[n]; int[] rightMax = new int[n]; // Compute leftMax int currentSum = 0, maxSum = Integer.MIN_VALUE; for (int i = 0; i < n; i++) { currentSum = Math.max(nums[i], currentSum + nums[i]); maxSum = Math.max(maxSum, currentSum); leftMax[i] = maxSum; } // Compute rightMax currentSum = 0; maxSum = Integer.MIN_VALUE; for (int i = n - 1; i >= 0; i--) { currentSum = Math.max(nums[i], currentSum + nums[i]); maxSum = Math.max(maxSum, currentSum); rightMax[i] = maxSum; } // Calculate the max sum of two non-overlapping subarrays int result = Integer.MIN_VALUE; for (int i = 0; i < n - 1; i++) { result = Math.max(result, leftMax[i] + rightMax[i + 1]); } return result; } public static void main(String[] args) { int[] nums = {1, -2, 3, 4, -5, 6}; System.out.println("Maximum Sum of Two Non-Overlapping Subarrays: " + maxSumTwoNonOverlappingSubarrays(nums)); } }
Leave a Comment