# 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
		2	0
		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 <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;

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;
}
else {
max = Math.max(max, a);
Long nextHighest = set.ceiling(a + 1);
if (nextHighest != null)
max = Math.max(max, a - nextHighest + m);
}
}
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 % m]
for x in a[1:]:
csum.append((csum[-1] + x) % m)

seen = 
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)```
```

## Simple Text Editor

In this challenge, you must implement a simple text editor. Initially, your editor contains an empty string, S. You must perform Q operations of the following 4 types: 1. append(W) - Append W string to the end of S. 2 . delete( k ) - Delete the last k characters of S. 3 .print( k ) - Print the kth character of S. 4 . undo( ) - Undo the last (not previously undone) operation of type 1 or 2,

## Poisonous Plants

There are a number of plants in a garden. Each of the plants has been treated with some amount of pesticide. After each day, if any plant has more pesticide than the plant on its left, being weaker than the left one, it dies. You are given the initial values of the pesticide in each of the plants. Determine the number of days after which no plant dies, i.e. the time after which there is no plan

## AND xor OR

Given an array of distinct elements. Let and be the smallest and the next smallest element in the interval where . . where , are the bitwise operators , and respectively. Your task is to find the maximum possible value of . Input Format First line contains integer N. Second line contains N integers, representing elements of the array A[] . Output Format Print the value

## Waiter

You are a waiter at a party. There is a pile of numbered plates. Create an empty answers array. At each iteration, i, remove each plate from the top of the stack in order. Determine if the number on the plate is evenly divisible ith the prime number. If it is, stack it in pile Bi. Otherwise, stack it in stack Ai. Store the values Bi in from top to bottom in answers. In the next iteration, do the

## Queue using Two Stacks

A queue is an abstract data type that maintains the order in which elements were added to it, allowing the oldest elements to be removed from the front and new elements to be added to the rear. This is called a First-In-First-Out (FIFO) data structure because the first element added to the queue (i.e., the one that has been waiting the longest) is always the first one to be removed. A basic que

## Castle on the Grid

You are given a square grid with some cells open (.) and some blocked (X). Your playing piece can move along any row or column until it reaches the edge of the grid or a blocked cell. Given a grid, a start and a goal, determine the minmum number of moves to get to the goal. Function Description Complete the minimumMoves function in the editor. minimumMoves has the following parameter(s):