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 <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;
}
                        


                        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;
}
                    


                        Solution in Java :

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);
   }
  }
}
                    


                        Solution in Python : 
                            
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

Compare two linked lists

You’re given the pointer to the head nodes of two linked lists. Compare the data in the nodes of the linked lists to check if they are equal. If all data attributes are equal and the lists are the same length, return 1. Otherwise, return 0. Example: list1=1->2->3->Null list2=1->2->3->4->Null The two lists have equal data attributes for the first 3 nodes. list2 is longer, though, so the lis

View Solution →

Merge two sorted linked lists

This challenge is part of a tutorial track by MyCodeSchool Given pointers to the heads of two sorted linked lists, merge them into a single, sorted linked list. Either head pointer may be null meaning that the corresponding list is empty. Example headA refers to 1 -> 3 -> 7 -> NULL headB refers to 1 -> 2 -> NULL The new list is 1 -> 1 -> 2 -> 3 -> 7 -> NULL. Function Description C

View Solution →

Get Node Value

This challenge is part of a tutorial track by MyCodeSchool Given a pointer to the head of a linked list and a specific position, determine the data value at that position. Count backwards from the tail node. The tail is at postion 0, its parent is at 1 and so on. Example head refers to 3 -> 2 -> 1 -> 0 -> NULL positionFromTail = 2 Each of the data values matches its distance from the t

View Solution →

Delete duplicate-value nodes from a sorted linked list

This challenge is part of a tutorial track by MyCodeSchool You are given the pointer to the head node of a sorted linked list, where the data in the nodes is in ascending order. Delete nodes and return a sorted list with each distinct value in the original list. The given head pointer may be null indicating that the list is empty. Example head refers to the first node in the list 1 -> 2 -

View Solution →

Cycle Detection

A linked list is said to contain a cycle if any node is visited more than once while traversing the list. Given a pointer to the head of a linked list, determine if it contains a cycle. If it does, return 1. Otherwise, return 0. Example head refers 1 -> 2 -> 3 -> NUL The numbers shown are the node numbers, not their data values. There is no cycle in this list so return 0. head refer

View Solution →

Find Merge Point of Two Lists

This challenge is part of a tutorial track by MyCodeSchool Given pointers to the head nodes of 2 linked lists that merge together at some point, find the node where the two lists merge. The merge point is where both lists point to the same node, i.e. they reference the same memory location. It is guaranteed that the two head nodes will be different, and neither will be NULL. If the lists share

View Solution →