#3654
Minimum Sum After Divisible Sum Deletions
MediumArrayHash TableDynamic ProgrammingPrefix 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)
Use prefix sums and a hash map to track remainders. This allows us to efficiently find subarrays whose sums are divisible by k.
⚙️
Algorithm
3 steps- 1Step 1: Compute prefix sums and their remainders when divided by k.
- 2Step 2: Use a hash map to track the first occurrence of each remainder.
- 3Step 3: Calculate the minimum remaining sum by considering deletions based on matching remainders.
solution.py11 lines
1def minSum(nums, k):
2 prefix_sum = 0
3 remainder_map = {0: -1}
4 total_sum = sum(nums)
5 for i, num in enumerate(nums):
6 prefix_sum += num
7 remainder = prefix_sum % k
8 if remainder in remainder_map:
9 total_sum -= prefix_sum - (remainder_map[remainder] + 1) * k
10 remainder_map[remainder] = prefix_sum
11 return total_sumℹ
Complexity note: The algorithm processes each element once and uses a hash map for quick lookups, leading to linear time complexity.
- 1Subarray sums are divisible by k when prefix sums have the same remainder.
- 2Using a hash map allows efficient tracking of prefix sums.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.