Maximum subarray sum modulo m
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.
[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<int>& 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<int> 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:
prefixi = (arr[0]+⋯+arr[i]) mod m.
Then, for a subarray ending at i and starting after j, the sum modulo mm is:
(prefixi−prefixj+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
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read