Maximum Subarray Sum
Problem Statement :
We define the following: A subarray of array a of length n is a contiguous segment from a[ i ] through a[ j ] where 0 <= i <= j < n. The sum of an array is the sum of its elements. Given an n element array of integers, a, and an integer, m , determine the maximum value of the sum of any of its subarrays modulo m. For example, Assume a = [1, 2, 3 ]and m = 2 . The following table lists all subarrays and their moduli: sum %2 [1] 1 1 [2] 2 0 [3] 3 1 [1,2] 3 1 [2,3] 5 1 [1,2,3] 6 0 The maximum modulus is . Function Description Complete the maximumSum function in the editor below. It should return a long integer that represents the maximum value of subarray sum % m. maximumSum has the following parameter(s): a: an array of long integers, the array to analyze m: a long integer, the modulo divisor Input Format The first line contains an integer q, the number of queries to perform. The next q pairs of lines are as follows: The first line contains two space-separated integers n and (long), m the length of a and the modulo divisor. The second line contains n space-separated long integers a[ i ]. Constraints 2 <= n <= 10^5 1 <= m <= 10^14 1 <= a[ i ] <= 10^18 2 <= the sum of n over all test cases <= 5 * 10^5 Output Format For each query, return the maximum value of subarray sum % m as a long integer. Sample Input 1 5 7 3 3 9 9 5 Sample Output 6
Solution :
Solution in C :
In C ++ :
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <set>
using namespace std;
long long mod;
long long arr[100005];
set<long long> f;
int main() {
int T;
scanf("%d", &T);
while (T--) {
int n;
scanf("%d%lld", &n, &mod);
for (int i = 0; i < n; ++i) {
scanf("%lld", &arr[i]);
arr[i] %= mod;
if (i) arr[i] = (arr[i] + arr[i - 1]) % mod;
}
f.clear();
f.insert(0);
set<long long>::iterator it;
long long ans = 0;
for (int i = 0; i < n; ++i) {
it = f.begin();
if (it != f.end())
ans = max(ans, arr[i] - *it);
it = f.upper_bound(arr[i]);
if (it != f.end())
ans = max(ans, (arr[i] - *it + mod) % mod);
f.insert(arr[i]);
}
printf("%lld\n", ans);
}
return 0;
}
In Java :
import java.util.*;
public class MaximizeSum {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
while (t-- > 0) {
int n = in.nextInt();
long m = Long.parseLong(in.next());
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
long num = Long.parseLong(in.next()) % m;
if (i == 0)
arr[i] = num;
else
arr[i] = (arr[i -1] + num) % m; // get cumulative sum
}
TreeSet<Long> set = new TreeSet<Long>();
long max = 0;
for (long a : arr) {
if (set.isEmpty()) {
max = a;
set.add(a);
}
else {
max = Math.max(max, a);
Long nextHighest = set.ceiling(a + 1);
if (nextHighest != null)
max = Math.max(max, a - nextHighest + m);
set.add(a);
}
}
System.out.println(max);
}
}
}
In C :
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
typedef unsigned long long ll ;
#define max(x,y) (x ^ ((x ^ y) & -(x < y)))
ll *A,*A2,M;
int intcmp(const void *aa, const void *bb)
{
const ll *a = aa, *b = bb;
return (*a < *b) ? -1 : (*a > *b);
}
ll bisect_left(ll bisect_len,ll x ) {
ll lo = 0;
ll hi = bisect_len;
ll mid = 0;
while ( lo < hi ) {
mid = (lo + hi) / 2;
if ( A2[mid] < x ) lo = mid+1;
else hi = mid;
}
if (lo != bisect_len && A2[lo] == x) {
return x;
}
if (lo == 0) return A2[bisect_len-1];
return A2[lo-1];
}
ll maxCrossingSum(ll l,ll m,ll h) {
ll s0 = 0,maxls = 0,mm=0,r1,r2,bisect_len;
ll i,j;
for ( i = m -1,j=0 ; i >= l && i!= -1; i--,j++ ) {
s0 = (s0 + A[i] ) % M;
if ( maxls < s0 ) maxls = s0;
A2[j] = s0;
}
bisect_len = j;
if ( bisect_len == 0) {
s0 = 0 ;maxls = 0;
for ( i = m ; i <=h ;i++ ) {
s0 = (s0 + A[i] ) % M;
if ( maxls < s0 ) maxls = s0;
}
return maxls;
}
qsort(A2, j, sizeof(ll), intcmp);
s0 = 0;
for ( i = m ; i <= h ; i++) {
s0 = (s0 + A[i] ) % M;
r1 = ( s0 + bisect_left(bisect_len,M-s0-1)) % M;
r2 = ( s0 + maxls ) % M;
mm = max(max(r1,r2),max(s0,mm));
}
return mm;
}
ll maxSum(ll l,ll h) {
ll m,r1,r2,r3;
if ( l == h ) return A[l] % M;
m = ( l + h ) / 2;
r1 = maxCrossingSum(l,m,h);
r2 = maxSum(l,m);
r3 = maxSum(m+1,h);
return max(max(r1,r2),r3);
}
int main() {
ll N,T,i,j,sum;
scanf("%llu",&T);
for (i = 0 ; i < T ; i++ ) {
scanf("%llu",&N);
scanf("%llu",&M);
A = malloc(N * sizeof(ll));
A2 = malloc(N * sizeof(ll));
for ( j = 0 ; j < N ; j++) {
scanf("%llu",&A[j]);
}
sum = maxSum(0,N-1);
printf("%llu\n",sum);
free(A);
free(A2);
}
return 0;
}
In Python3 :
import bisect
t = int(input())
for _ in range(t):
n, m = map(int, input().split())
a = list(map(int, input().split()))
csum = [a[0] % m]
for x in a[1:]:
csum.append((csum[-1] + x) % m)
seen = [0]
mx = -1
for s in csum:
idx = bisect.bisect_left(seen, s)
if idx < len(seen):
mx = max(mx, s, (s - seen[idx]) % m)
else:
mx = max(mx, s)
bisect.insort_left(seen, s)
#print(seen)
print(mx)
View More Similar Problems
Insert a Node at the Tail of a Linked List
You are given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer. Insert this node at the tail of the linked list and return the head node of the linked list formed after inserting this new node. The given head pointer may be null, meaning that the initial list is empty. Input Format: You have to complete the SinglyLink
View Solution →Insert a Node at the head of a Linked List
Given a pointer to the head of a linked list, insert a new node before the head. The next value in the new node should point to head and the data value should be replaced with a given value. Return a reference to the new head of the list. The head pointer given may be null meaning that the initial list is empty. Function Description: Complete the function insertNodeAtHead in the editor below
View Solution →Insert a node at a specific position in a linked list
Given the pointer to the head node of a linked list and an integer to insert at a certain position, create a new node with the given integer as its data attribute, insert this node at the desired position and return the head node. A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The head pointer given may be null meaning that the initial list is e
View Solution →Delete a Node
Delete the node at a given position in a linked list and return a reference to the head node. The head is at position 0. The list may be empty after you delete the node. In that case, return a null value. Example: list=0->1->2->3 position=2 After removing the node at position 2, list'= 0->1->-3. Function Description: Complete the deleteNode function in the editor below. deleteNo
View Solution →Print in Reverse
Given a pointer to the head of a singly-linked list, print each data value from the reversed list. If the given list is empty, do not print anything. Example head* refers to the linked list with data values 1->2->3->Null Print the following: 3 2 1 Function Description: Complete the reversePrint function in the editor below. reversePrint has the following parameters: Sing
View Solution →Reverse a linked list
Given the pointer to the head node of a linked list, change the next pointers of the nodes so that their order is reversed. The head pointer given may be null meaning that the initial list is empty. Example: head references the list 1->2->3->Null. Manipulate the next pointers of each node in place and return head, now referencing the head of the list 3->2->1->Null. Function Descriptio
View Solution →