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 :



title-img


                            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

Lazy White Falcon

White Falcon just solved the data structure problem below using heavy-light decomposition. Can you help her find a new solution that doesn't require implementing any fancy techniques? There are 2 types of query operations that can be performed on a tree: 1 u x: Assign x as the value of node u. 2 u v: Print the sum of the node values in the unique path from node u to node v. Given a tree wi

View Solution →

Ticket to Ride

Simon received the board game Ticket to Ride as a birthday present. After playing it with his friends, he decides to come up with a strategy for the game. There are n cities on the map and n - 1 road plans. Each road plan consists of the following: Two cities which can be directly connected by a road. The length of the proposed road. The entire road plan is designed in such a way that if o

View Solution →

Heavy Light White Falcon

Our lazy white falcon finally decided to learn heavy-light decomposition. Her teacher gave an assignment for her to practice this new technique. Please help her by solving this problem. You are given a tree with N nodes and each node's value is initially 0. The problem asks you to operate the following two types of queries: "1 u x" assign x to the value of the node . "2 u v" print the maxim

View Solution →

Number Game on a Tree

Andy and Lily love playing games with numbers and trees. Today they have a tree consisting of n nodes and n -1 edges. Each edge i has an integer weight, wi. Before the game starts, Andy chooses an unordered pair of distinct nodes, ( u , v ), and uses all the edge weights present on the unique path from node u to node v to construct a list of numbers. For example, in the diagram below, Andy

View Solution →

Heavy Light 2 White Falcon

White Falcon was amazed by what she can do with heavy-light decomposition on trees. As a resut, she wants to improve her expertise on heavy-light decomposition. Her teacher gave her an another assignment which requires path updates. As always, White Falcon needs your help with the assignment. You are given a tree with N nodes and each node's value Vi is initially 0. Let's denote the path fr

View Solution →

Library Query

A giant library has just been inaugurated this week. It can be modeled as a sequence of N consecutive shelves with each shelf having some number of books. Now, being the geek that you are, you thought of the following two queries which can be performed on these shelves. Change the number of books in one of the shelves. Obtain the number of books on the shelf having the kth rank within the ra

View Solution →