Nikita and the Game


Problem Statement :


Nikita just came up with a new array game. The rules are as follows:

Initially, Nikita has an array of integers.

In each move, Nikita must partition the array into 2 non-empty contiguous parts such that the sum of the elements in the left partition is equal to the sum of the elements in the right partition. If Nikita can make such a move, she gets 1 point; otherwise, the game ends.

After each successful move, Nikita discards either the left partition or the right partition and continues playing by using the remaining partition as array arr.

Nikita loves this game and wants your help getting the best score possible. Given arr, can you find and print the maximum number of points she can score?

For example, Nikita starts with the array arr = [1,2,3,6]. She first splits it into a1 = [1,2,3] and a2 = [6], then discards a2. arr = a1->a1 = [1,2], a2 = [3]. Discard a2 leaving arr = [1,2]. This cannot be further split, so Nikita scored 2.

Function Description

Complete the arraySplitting function in the editor below. It should return an integer that reperesents the number of times Nikita can split the array.

arraySplitting has the following parameter(s):

arr: an array of integers
Input Format

The first line contains an integer t, the number of test cases.

Each of the next t pairs of lines is as follows:

The first line contains an integer n, the size of array arr.
The next line contains n space-separated integers arr[i].

Constraints

1 <= t<= 10
1 <= n <= 2^14
0 <= arr[i] <=10^9



Solution :



title-img


                            Solution in C :

In C++ :





//start of jonathanirvings' template v3.0.1 (BETA)

#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <deque>
#include <string>
#include <string.h>
#include <vector>
#include <stack>
#include <queue>
#include <math.h>
#include <stdlib.h>
#include <map>
#include <set>
#include <time.h>
#include <bitset>
#include <list>
#include <assert.h>
#include <time.h>
using namespace std;

typedef long long LL;
typedef pair<int,int> pii;
typedef pair<LL,LL> pll;
typedef pair<string,string> pss;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<pii> vii;
typedef vector<LL> vl;
typedef vector<vl> vvl;

double EPS = 1e-9;
int INF = 1000000005;
long long INFF = 1000000000000000005LL;
double PI = acos(-1);
int dirx[8] = {-1,0,0,1,-1,-1,1,1};
int diry[8] = {0,1,-1,0,-1,1,-1,1};

#ifdef TESTING
  #define DEBUG fprintf(stderr,"====TESTING====\n")
  #define VALUE(x) cerr << "The value of " << #x << " is " << x << endl
  #define debug(...) fprintf(stderr, __VA_ARGS__)
#else
  #define DEBUG 
  #define VALUE(x)
  #define debug(...)
#endif

#define FOR(a,b,c) for (int (a)=(b);(a)<(c);++(a))
#define FORN(a,b,c) for (int (a)=(b);(a)<=(c);++(a))
#define FORD(a,b,c) for (int (a)=(b);(a)>=(c);--(a))
#define FORSQ(a,b,c) for (int (a)=(b);(a)*(a)<=(c);++(a))
#define FORC(a,b,c) for (char (a)=(b);(a)<=(c);++(a))
#define REP(i,n) FOR(i,0,n)
#define REPN(i,n) FORN(i,1,n)
#define MAX(a,b) a = max(a,b)
#define MIN(a,b) a = min(a,b)
#define SQR(x) ((x) * (x))
#define RESET(a,b) memset(a,b,sizeof(a))
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define ALL(v) v.begin(),v.end()
#define ALLA(arr,sz) arr,arr+sz
#define SIZE(v) (int)v.size()
#define SORT(v) sort(ALL(v))
#define REVERSE(v) reverse(ALL(v))
#define SORTA(arr,sz) sort(ALLA(arr,sz))
#define REVERSEA(arr,sz) reverse(ALLA(arr,sz))
#define PERMUTE next_permutation
#define TC(t) while(t--)

inline string IntToString(LL a){
  char x[100];
  sprintf(x,"%lld",a); string s = x;
  return s;
}

inline LL StringToInt(string a){
  char x[100]; LL res;
  strcpy(x,a.c_str()); sscanf(x,"%lld",&res);
  return res;
}

inline string GetString(void){
  char x[1000005];
  scanf("%s",x); string s = x;
  return s;
}

inline string uppercase(string s){
  int n = SIZE(s); 
  REP(i,n) if (s[i] >= 'a' && s[i] <= 'z') s[i] = s[i] - 'a' + 'A';
  return s;
}

inline string lowercase(string s){
  int n = SIZE(s); 
  REP(i,n) if (s[i] >= 'A' && s[i] <= 'Z') s[i] = s[i] - 'A' + 'a';
  return s;
}

inline void OPEN (string s) {
  freopen ((s + ".in").c_str (), "r", stdin);
  freopen ((s + ".out").c_str (), "w", stdout);
}

//end of jonathanirvings' template v3.0.1 (BETA)

int data[17000];
int n;
int T;

int count(int L,int R)
{
  if (L == R) return 0;
  LL tot = 0;
  FORN(i,L,R) tot += data[i];
  if (tot % 2 == 1) return 0;
  LL now = 0;
  FORN(i,L,R)
  {
    now += data[i];
    if (now == tot/2)
    {
      return 1 + max(count(L,i),count(i+1,R));
    }
  }
  return 0;
}

int main()
{
  scanf("%d",&T);
  TC(T)
  {
    scanf("%d",&n);
    REP(i,n) scanf("%d",&data[i]);
    int risan = count(0,n-1);
    printf("%d\n",risan);
  }
  return 0;
}








In Java :






import java.util.*;
import java.io.*;

public class B
{
   public static void main(String[] args) throws Exception
   {
      FastScanner in = new FastScanner(System.in);
      PrintWriter out = new PrintWriter(System.out);
      int T = in.nextInt();
      while (T-->0) new B(in, out);
      out.close();
   }
   int N;
   int[] vs;
   int go(int i, int j)
   {
      long sum = 0;
      for (int x=i; x<=j; x++)
         sum += vs[x];
      if (sum % 2 != 0) return 0;
      sum /= 2;

      long ss = 0;
      for (int x=i; x<j; x++)
      {
         ss += vs[x];
         if (ss == sum)
            return 1 + Math.max(go(i, x), go(x+1, j));
      }
      return 0;
   }

   public B(FastScanner in, PrintWriter out)
   {
      N = in.nextInt();
      vs = new int[N];
      for (int i=0; i<N; i++)
         vs[i] = in.nextInt();

      long res = go(0, N-1);
      out.println(res);
   }
}

class FastScanner{
   private InputStream stream;
   private byte[] buf = new byte[1024];
   private int curChar;
   private int numChars;

   public FastScanner(InputStream stream)
   {
      this.stream = stream;
   }

   int read()
   {
      if (numChars == -1)
         throw new InputMismatchException();
      if (curChar >= numChars){
         curChar = 0;
         try{
            numChars = stream.read(buf);
         } catch (IOException e) {
            throw new InputMismatchException();
         }
         if (numChars <= 0)
            return -1;
      }
      return buf[curChar++];
   }

   boolean isSpaceChar(int c)
   {
      return c==' '||c=='\n'||c=='\r'||c=='\t'||c==-1;
   }
   
   boolean isEndline(int c)
   {
      return c=='\n'||c=='\r'||c==-1;
   }

   int nextInt()
   {
      return Integer.parseInt(next());
   }
   
   long nextLong()
   {
      return Long.parseLong(next());
   }

   double nextDouble()
   {
      return Double.parseDouble(next());
   }

   String next(){
      int c = read();
      while (isSpaceChar(c))
         c = read();
      StringBuilder res = new StringBuilder();
      do{
         res.appendCodePoint(c);
         c = read();
      }while(!isSpaceChar(c));
      return res.toString();
   }
   
   String nextLine(){
      int c = read();
      while (isEndline(c))
         c = read();
      StringBuilder res = new StringBuilder();
      do{
         res.appendCodePoint(c);
         c = read();
      }while(!isEndline(c));
      return res.toString();
   }
}








In C :





#include<stdio.h>
typedef long long unsigned U;
typedef unsigned u;
u A[222222];
u F(u l,u r,U s)
{
	u m=l-1,i,j;U x=0llu;
	for(;++m<=r;)
	{
		x+=A[m];
		if((x<<1)>s)break;
		if((x<<1)==s)
		{
			i=F(l,m,x);
			if(i<(j=F(m+1,r,x)))i=j;
			return i+1;
		}
	}
	return 0;
}
int main()
{
	u t,n,i;U s;
	for(scanf("%u",&t);t--;)
	{
		scanf("%u",&n);s=0llu;
		for(i=-1;++i<n;s+=A[i])scanf("%u",A+i);
		if(!s){printf("%u\n",n-1);continue;}
		printf("%u\n",F(0,n-1,s));
	}
	return 0;
}








In Python3 :





import math

def solve(a):
    s = sum(a)
    if s % 2:
        return 0
    s //= 2
    t = 0
    for i in range(len(a)):
        t += a[i]
        if t == s:
            #print(sum(a[:i + 1]), sum(a[i + 1:]))
            return 1 + max(solve(a[:i + 1]), solve(a[i + 1:]))
        if t > s:
            return 0
        
def solve0(n):
    return n - 1

t = int(input().strip())
for test in range(t):
    n = int(input().strip())
    a = list(map(int, input().strip().split()))
    if sum(a) == 0:
        print(solve0(n))
    else:
        print(solve(a))
                        








View More Similar Problems

Sparse Arrays

There is a collection of input strings and a collection of query strings. For each query string, determine how many times it occurs in the list of input strings. Return an array of the results. Example: strings=['ab', 'ab', 'abc'] queries=['ab', 'abc', 'bc'] There are instances of 'ab', 1 of 'abc' and 0 of 'bc'. For each query, add an element to the return array, results=[2,1,0]. Fun

View Solution →

Array Manipulation

Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each of the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array. Example: n=10 queries=[[1,5,3], [4,8,7], [6,9,1]] Queries are interpreted as follows: a b k 1 5 3 4 8 7 6 9 1 Add the valu

View Solution →

Print the Elements of a Linked List

This is an to practice traversing a linked list. Given a pointer to the head node of a linked list, print each node's data element, one per line. If the head pointer is null (indicating the list is empty), there is nothing to print. Function Description: Complete the printLinkedList function in the editor below. printLinkedList has the following parameter(s): 1.SinglyLinkedListNode

View Solution →

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 →