Problem 22: Maximum Subarray Sum Modulo
Problem Statement: Given an array of n integers and an integer m, find the maximum value of the sum of a subarray modulo m.
Input
The first line contains two integers n and m. The second line contains n spaceāseparated integers.
Output
Print the maximum subarray sum modulo m.
Examples
Input:
3 7
3 3 9
Output:
6
Solution in C++
#include <bits/stdc++.h>
using namespace std;
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
long long n, m; cin >> n >> m;
vector<long long> a(n);
for(int i = 0; i < n; i++)
cin >> a[i];
set<long long> prefixSet;
long long ans = 0, prefix = 0;
prefixSet.insert(0);
for (int i = 0; i < n; i++){
prefix = (prefix + a[i]) % m;
ans = max(ans, prefix);
auto it = prefixSet.lower_bound(prefix + 1);
if(it != prefixSet.end()){
ans = max(ans, (prefix - *it + m) % m);
}
prefixSet.insert(prefix);
}
cout << ans << "\n";
return 0;
}