Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find the maximum sum of the subarray modulo by m in Python
Finding the maximum sum of a subarray modulo m is a challenging problem that requires tracking cumulative sums and using binary search for efficiency. This problem asks us to find the subarray with the largest sum when taken modulo m.
Problem Understanding
Given an array nums and integer m, we need to find the maximum value of any subarray sum modulo m. A subarray is a contiguous sequence of elements.
For example, with nums = [1,5,7,3] and m = 5:
- [1] mod 5 = 1
- [5] mod 5 = 0
- [7] mod 5 = 2
- [3] mod 5 = 3
- [1,5] mod 5 = 1
- [5,7] mod 5 = 2
- [7,3] mod 5 = 0
- [1,5,7] mod 5 = 3
- [5,7,3] mod 5 = 0
- [1,5,7,3] mod 5 = 1
The maximum value is 3.
Algorithm Approach
The solution uses cumulative sums and binary search:
- Calculate cumulative sums modulo m
- For each cumulative sum, find the best previous sum to subtract
- Use binary search to efficiently find the optimal subtraction point
- Track the maximum result throughout the process
Implementation
import bisect
def solve(nums, m):
# Calculate cumulative sums modulo m
csum = [nums[0] % m]
for x in nums[1:]:
csum.append((csum[-1] + x) % m)
seen = [0] # Track seen cumulative sums
max_sum = -1
for s in csum:
# Find insertion point using binary search
idx = bisect.bisect_left(seen, s)
if idx < len(seen):
# Calculate subarray sum: current - previous
max_sum = max(max_sum, s, (s - seen[idx]) % m)
else:
max_sum = max(max_sum, s)
# Insert current sum to maintain sorted order
bisect.insort_left(seen, s)
return max_sum
# Test the function
nums = [1, 5, 7, 3]
m = 5
result = solve(nums, m)
print(f"Maximum subarray sum modulo {m}: {result}")
Maximum subarray sum modulo 5: 3
How It Works
The algorithm works by maintaining cumulative sums and using the property that subarray sum from index i to j equals csum[j] - csum[i-1]. The binary search helps find the optimal previous cumulative sum to subtract, maximizing the result modulo m.
Example with Different Input
# Test with another example
nums = [3, 3, 9, 9, 5]
m = 7
result = solve(nums, m)
print(f"Input: {nums}, m = {m}")
print(f"Maximum subarray sum modulo {m}: {result}")
Input: [3, 3, 9, 9, 5], m = 7 Maximum subarray sum modulo 7: 6
Time Complexity
The time complexity is O(n log n) where n is the length of the array, due to the binary search operations. The space complexity is O(n) for storing cumulative sums and the seen array.
Conclusion
This solution efficiently finds the maximum subarray sum modulo m using cumulative sums and binary search. The key insight is using the difference between cumulative sums to represent subarray sums and optimizing with binary search.
