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));
`
Similar Reads
- Maximum subarray product modulo M Given an array, arr[] of size N and a positive integer M, the task is to find the maximum subarray product modulo M and the minimum length of the maximum product subarray. Examples: Input: arr[] = {2, 3, 4, 2}, N = 4, M = 5Output: Maximum subarray product is 4 Minimum length of the maximum product s 8 min read
- CSES Solutions - Maximum Subarray Sum Given an array arr[] of N integers, your task is to find the maximum sum of values in a contiguous, nonempty subarray. Examples: Input: N = 8, arr[] = {-1, 3, -2, 5, 3, -5, 2, 2}Output: 9Explanation: The subarray with maximum sum is {3, -2, 5, 3} with sum = 3 - 2 + 5 + 3 = 9. Input: N = 6, arr[] = { 5 min read
- CSES Solutions - Maximum Subarray Sum II Given an array arr[] of N integers, your task is to find the maximum sum of values in a contiguous subarray with length between A and B. Examples: Input: N = 8, A = 1, B = 2, arr[] = {-1, 3, -2, 5, 3, -5, 2, 2}Output: 8Explanation: The subarray with maximum sum is {5, 3}, the length between 1 and 2, 12 min read
- Maximum sum bitonic subarray Given an array containing n numbers. The problem is to find the maximum sum bitonic subarray. A bitonic subarray is a subarray in which elements are first increasing and then decreasing. A strictly increasing or strictly decreasing subarray is also considered a bitonic subarray. Time Complexity of O 15+ min read
- Maximum Circular Subarray Sum Given a circular array arr[] of size n, find the maximum possible sum of a non-empty subarray. Examples: Input: arr[] = {8, -8, 9, -9, 10, -11, 12}Output: 22Explanation: Circular Subarray {12, 8, -8, 9, -9, 10} has the maximum sum, which is 22. Input: arr[] = {10, -3, -4, 7, 6, 5, -4, -1}Output: 23 15+ min read
- Print subarray with maximum sum Given an array arr[], the task is to print the subarray having maximum sum. Examples: Input: arr[] = {2, 3, -8, 7, -1, 2, 3}Output: 11Explanation: The subarray {7, -1, 2, 3} has the largest sum 11. Input: arr[] = {-2, -5, 6, -2, -3, 1, 5, -6}Output: {6, -2, -3, 1, 5}Explanation: The subarray {6, -2, 13 min read
- Maximum sum subarray of size range [L, R] Given an integer array arr[] of size N and two integer L and R. The task is to find the maximum sum subarray of size between L and R (both inclusive). Example: Input: arr[] = {1, 2, 2, 1}, L = 1, R = 3 Output: 5 Explanation: Subarray of size 1 are {1}, {2}, {2}, {1} and maximum sum subarray = 2 for 8 min read
- Maximum Sum Alternating Subarray Given an array arr[] of size N, the task is to find the maximum alternating sum of a subarray possible for a given array. Alternating Subarray Sum: Considering a subarray {arr[i], arr[j]}, alternating sum of the subarray is arr[i] - arr[i + 1] + arr[i + 2] - ........ (+ / -) arr[j]. Examples: Input: 6 min read
- Maximum sum submatrix Prerequisite: Kadane's algorithm Given a 2D array arr[][] of dimension N*M, the task is to find the maximum sum sub-matrix from the matrix arr[][]. Examples: Input: arr[][] = {{0, -2, -7, 0 }, { 9, 2, -6, 2 }, { -4, 1, -4, 1 }, { -1, 8, 0, -2}}Output: 15Explanation: The submatrix {{9, 2}, {-4, 1}, { 15+ min read
- Maximum Subarray Sum - Kadane's Algorithm Given an array arr[], the task is to find the subarray that has the maximum sum and return its sum. Examples: Input: arr[] = {2, 3, -8, 7, -1, 2, 3}Output: 11Explanation: The subarray {7, -1, 2, 3} has the largest sum 11. Input: arr[] = {-2, -4}Output: -2Explanation: The subarray {-2} has the larges 10 min read