#3026
Maximum Good Subarray Sum
MediumArrayHash TablePrefix SumHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses a HashMap to store prefix sums, allowing us to quickly check for good subarrays by leveraging the properties of prefix sums and the required difference k.
⚙️
Algorithm
6 steps- 1Step 1: Initialize a HashMap to store prefix sums and their corresponding indices.
- 2Step 2: Initialize a variable to keep track of the maximum sum found.
- 3Step 3: Iterate through the array, calculating the prefix sum as you go.
- 4Step 4: For each element, check if the prefix sum minus k or plus k exists in the HashMap.
- 5Step 5: If it exists, calculate the subarray sum and update the maximum sum if this sum is greater.
- 6Step 6: Store the current prefix sum in the HashMap.
solution.py12 lines
1def maxGoodSubarraySum(nums, k):
2 prefix_sum = 0
3 max_sum = 0
4 prefix_map = {}
5 for i in range(len(nums)):
6 prefix_sum += nums[i]
7 if (prefix_sum - k) in prefix_map:
8 max_sum = max(max_sum, prefix_sum - prefix_map[prefix_sum - k])
9 if (prefix_sum + k) in prefix_map:
10 max_sum = max(max_sum, prefix_sum - prefix_map[prefix_sum + k])
11 prefix_map[prefix_sum] = prefix_sum
12 return max_sumℹ
Complexity note: This complexity is achieved because we only traverse the array once and use a HashMap to store prefix sums, leading to linear time complexity.
- 1Understanding the properties of prefix sums can significantly reduce the time complexity of subarray problems.
- 2Using a HashMap allows for quick lookups, which is essential for optimizing the solution.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.