Maximum subarray sum modulo m (original) (raw)
Last Updated : 24 Mar, 2025
Given an array of **n elements and an integer m. The task is to find the maximum value of the sum of its subarray modulo m i.e find the sum of each subarray mod m and print the maximum value of this modulo operation.
**Examples:
**Input: arr[] = {10, 7, 18}, m = 13
**Output: 12
**Explanation: All subarrays and their modulo values:{10}
=> 10 mod 13 = 10{7}
=> 7 mod 13 = 7{18}
=> 18 mod 13 = 5{10, 7}
=> 17 mod 13 = 4{7, 18}
=> 25 mod 13 = 12{10, 7, 18}
=> 35 mod 13 = 9**Input: arr[] = {3, 3, 9, 9, 5}, m = 7
**Output: 6
**Explanation: The subarray {3, 3} has maximum sub-array sum modulo 7.
Table of Content
- [Naive Approach] Checking All Subarrays - O(n^2) time and O(1) space
- [Efficient Approach] Using Prefix Sum - O(n log(n)) time and O(n) space
[Naive Approach] Checking All Subarrays - O(n^2) time and O(1) space
The approach checks all possible subarrays, computes their sum modulo
m
, and tracks the highest remainder found.
C++ `
#include <bits/stdc++.h> using namespace std;
// Function to find the maximum subarray sum modulo m int maxSubMod(vector& arr, int m) { int n = arr.size(); int maxMod = 0;
// Iterate over all possible subarrays
for (int i = 0; i < n; i++) {
int sum = 0;
for (int j = i; j < n; j++) {
// Compute sum of subarray arr[i...j]
sum += arr[j];
// Update max modulo result
maxMod = max(maxMod, sum % m);
}
}
return maxMod;
}
int main() { vector arr = {3, 3, 9, 9, 5}; int m = 7; cout << maxSubMod(arr, m) << endl; return 0; }
Java
// Function to find the maximum subarray sum modulo m public class GfG { public static int maxSubMod(int[] arr, int m) { int n = arr.length; int maxMod = 0;
// Iterate over all possible subarrays
for (int i = 0; i < n; i++) {
int sum = 0;
for (int j = i; j < n; j++) {
// Compute sum of subarray arr[i...j]
sum += arr[j];
// Update max modulo result
maxMod = Math.max(maxMod, sum % m);
}
}
return maxMod;
}
public static void main(String[] args) {
int[] arr = {3, 3, 9, 9, 5};
int m = 7;
System.out.println(maxSubMod(arr, m));
}
}
Python
Function to find the maximum subarray sum modulo m
def maxSubMod(arr, m): n = len(arr) maxMod = 0
# Iterate over all possible subarrays
for i in range(n):
sum = 0
for j in range(i, n):
# Compute sum of subarray arr[i...j]
sum += arr[j]
# Update max modulo result
maxMod = max(maxMod, sum % m)
return maxMod
if name == 'main': arr = [3, 3, 9, 9, 5] m = 7 print(maxSubMod(arr, m))
C#
// Function to find the maximum subarray sum modulo m using System; using System.Linq;
class GfG { public static int MaxSubMod(int[] arr, int m) { int n = arr.Length; int maxMod = 0;
// Iterate over all possible subarrays
for (int i = 0; i < n; i++) {
int sum = 0;
for (int j = i; j < n; j++) {
// Compute sum of subarray arr[i...j]
sum += arr[j];
// Update max modulo result
maxMod = Math.Max(maxMod, sum % m);
}
}
return maxMod;
}
static void Main() {
int[] arr = {3, 3, 9, 9, 5};
int m = 7;
Console.WriteLine(MaxSubMod(arr, m));
}
}
JavaScript
// Function to find the maximum subarray sum modulo m function maxSubMod(arr, m) { let n = arr.length; let maxMod = 0;
// Iterate over all possible subarrays
for (let i = 0; i < n; i++) {
let sum = 0;
for (let j = i; j < n; j++) {
// Compute sum of subarray arr[i...j]
sum += arr[j];
// Update max modulo result
maxMod = Math.max(maxMod, sum % m);
}
}
return maxMod;
}
const arr = [3, 3, 9, 9, 5]; const m = 7; console.log(maxSubMod(arr, m));
`
[Efficient Approach] Using Prefix Sum - O(n log(n)) time and O(n) space
The idea is to use prefix sums because any subarray's sum can be quickly computed as the difference between two prefix sums. By taking modulo m at each step, we have:
**prefix i **= (arr[0]+⋯+arr[i]) mod m.
Then, for a subarray ending at i and starting after j, the sum modulo mm is:
****(prefix** i −prefix j +m) mod m.
This formula is optimal because by choosing the smallest prefix prefixj that is greater than prefixi, we minimize the deduction from prefixi and maximize the result.
We mainly have two operations in above algorithm.
- Store all prefixes.
- For current prefixi, find the smallest value greater than or equal to prefixi + 1. C++ `
#include <bits/stdc++.h> using namespace std;
// Function to return the maximum subarray // sum modulo m. int maxSub(int arr[], int n, int m) {
int pre = 0, mx = 0;
// Create an ordered set to store prefix
// sums for efficient searching.
set<int> s;
s.insert(0);
// Loop through each element in the array.
for (int i = 0; i < n; i++) {
pre = (pre + arr[i]) % m;
mx = max(mx, pre);
// Find the smallest prefix in the set
// greater than the current prefix.
auto it = s.lower_bound(pre + 1);
// If such a prefix exists, calculate
// the potential maximum modulo sum.
if (it != s.end())
mx = max(mx, (pre - *it + m) % m);
// Insert the current prefix sum into
// the set for future comparisons.
s.insert(pre);
}
return mx;
}
int main() { int arr[] = {3, 3, 9, 9, 5}; int n = sizeof(arr) / sizeof(arr[0]); int m = 7; cout << maxSub(arr, n, m) << endl; return 0; }
Python
Function to return the maximum subarray sum modulo m.
def max_sub(arr, n, m): pre = 0 mx = 0
# Create a set to store prefix
// sums for efficient searching.
s = set()
s.add(0)
# Loop through each element in the array.
for i in range(n):
pre = (pre + arr[i]) % m
mx = max(mx, pre)
# Find the smallest prefix in the set greater
# than the current prefix.
it = next((x for x in s if x > pre), None)
# If such a prefix exists, calculate the
# potential maximum modulo sum.
if it is not None:
mx = max(mx, (pre - it + m) % m)
# Insert the current prefix sum into the
# set for future comparisons.
s.add(pre)
return mx
arr = [3, 3, 9, 9, 5] n = len(arr) m = 7 print(max_sub(arr, n, m))
JavaScript
// Function to return the maximum subarray sum modulo m. function maxSub(arr, n, m) { let pre = 0, mx = 0;
// Create a set to store prefix sums
// for efficient searching.
const s = new Set();
s.add(0);
// Loop through each element in the array.
for (let i = 0; i < n; i++) {
pre = (pre + arr[i]) % m;
mx = Math.max(mx, pre);
// Find the smallest prefix in the
// set greater than the current prefix.
for (let x of s) {
if (x > pre) {
mx = Math.max(mx, (pre - x + m) % m);
break;
}
}
// Insert the current prefix sum into
// the set for future comparisons.
s.add(pre);
}
return mx;
}
const arr = [3, 3, 9, 9, 5]; const n = arr.length; const m = 7; console.log(maxSub(arr, n, m));
`