#3381

Maximum Subarray Sum With Length Divisible by K

Medium
ArrayHash TablePrefix SumHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses prefix sums and a HashMap to efficiently track the minimum prefix sums for each modulo k value. This allows us to calculate the maximum sum of subarrays with lengths divisible by k in linear time.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a prefix sum variable and a HashMap to store minimum prefix sums for each modulo k value.
  2. 2Step 2: Iterate through the array, updating the prefix sum.
  3. 3Step 3: For each prefix sum, calculate the current modulo k value.
  4. 4Step 4: If this modulo value has been seen before, calculate the potential maximum sum using the difference between the current prefix sum and the minimum prefix sum for that modulo value.
  5. 5Step 5: Update the HashMap with the minimum prefix sum for the current modulo value.
solution.py14 lines
1# Full working Python code
2
3def maxSubarraySumDivK(nums, k):
4    prefix_sum = 0
5    min_prefix = {0: 0}
6    max_sum = float('-inf')
7    for i, num in enumerate(nums):
8        prefix_sum += num
9        mod = prefix_sum % k
10        if mod in min_prefix:
11            max_sum = max(max_sum, prefix_sum - min_prefix[mod])
12        else:
13            min_prefix[mod] = prefix_sum
14    return max_sum

Complexity note: This complexity is linear because we only traverse the array once and use a HashMap to store prefix sums, which allows for efficient lookups.

  • 1Using prefix sums allows us to efficiently calculate subarray sums.
  • 2HashMaps can be used to track minimum prefix sums for each modulo value, enabling quick lookups.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.