gpt-4o-2024-08-06· OpenAI
WildChat-4.8M (AI2)
Give simple, common, and optimised Java solution class Solution 0 pres spRint…
- User
Give simple, common, and optimised Java solution
class Solution 0 pres spRint maxSubArrayLen (int[l nums, int k)
- Assistant
To solve the problem of finding the maximum length of a subarray that sums to a given value
k, you can use a hash map to store the cumulative sum and its corresponding index. Here’s a simple and optimized Java solution:import java.util.HashMap; class Solution { public int maxSubArrayLen(int[] nums, int k) { // Map to store the cumulative sum up to each index HashMap<Integer, Integer> sumIndexMap = new HashMap<>(); // Initialize with cumulative sum 0 at index -1 for edge cases sumIndexMap.put(0, -1); int maxLen = 0; int cumulativeSum = 0; for (int i = 0; i < nums.length; i++) { // Add current number to the cumulative sum cumulativeSum += nums[i]; // Check if there is a subarray that sums to k if (sumIndexMap.containsKey(cumulativeSum - k)) { // Update the max length if this subarray is longer maxLen = Math.max(maxLen, i - sumIndexMap.get(cumulativeSum - k)); } // Only add cumulative sum to the map if it's not already present // This ensures we get the longest subarray by keeping the earliest found index if (!sumIndexMap.containsKey(cumulativeSum)) { sumIndexMap.put(cumulativeSum, i); } } return maxLen; } }