1669F - Eating Candies - CodeForces Solution


binary search data structures greedy two pointers *1100

Please click on ads to support us..

Python Code:

import sys,os,math,cmath,timeit,functools,operator,bisect
from sys import stdin,stdout,setrecursionlimit
from io import BytesIO, IOBase
from collections import defaultdict as dd , Counter
from math import factorial , gcd
from queue import PriorityQueue
from heapq import merge, heapify, heappop, heappush
try :
    from functools import cache , lru_cache
    from sortedcontainers import *
except :
    pass 

ONLINE_JUDGE = __debug__

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        import os
        self.os = os
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
        self.BUFSIZE = 8192

    def read(self):
        while True:
            a = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.BUFSIZE))
            if not a:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(a), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            a = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.BUFSIZE))
            self.newlines = a.count(b"\n") + (not a)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(a), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            self.os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


stdin, stdout = IOWrapper(stdin), IOWrapper(stdout)

input = lambda: stdin.readline().rstrip("\r\n")

start = timeit.default_timer()

primes = []
mod=10**9+7
MOD=998244353


def seive(n):
    a = []
    prime = [True for i in range(n+1)] 
    p = 2
    while (p * p <= n): 
        if (prime[p] == True): 
            for i in range(p ** 2,n + 1, p): 
                prime[i] = False
        p = p + 1
    for p in range(2,n + 1): 
        if prime[p]: 
            primes.append(p)

def lower_bound(arr, n, k):
    start = 0
    end = n-1
    while start <= end:
        mid = (start+end)//2
        if arr[mid] == k:
            return mid
        elif arr[mid] > k:
            if mid > 0:
                if arr[mid-1] < k:
                    return (mid-1)
            else:
                return -1
        else:
            if mid < (n-1):
                if arr[mid+1] > k:
                    return mid
            else:
                return mid

def upper_bound(arr, n, k):
    start = 0
    end = n-1
    while start <= end:
        mid = (start+end)//2
        if arr[mid] == k:
            return mid
        elif arr[mid] > k:
            if mid > 0:
                if arr[mid-1] < k:
                    return (mid)
            else:
                return mid
        else:
            if mid < (n-1):
                if arr[mid+1] > k:
                    return (mid+1)
            else:
                return -1

def is_sorted(arr):
    return all(arr[i]<=arr[i+1] for i in range(len(arr)-1))

def invmod(n):
    return pow(n,mod-2,mod)

def binary_search(a,x,lo=0,hi=None):
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        midval = a[mid]
        if midval < x:
            lo = mid+1
        elif midval > x: 
            hi = mid
        else:
            return mid
    return -1

def ceil(a:int,b:int)->int :
    return (a+b-1)//b

def yn(x):
    if x :
        print("YES")
    else :
        print("NO")

def nCr(n,r):
    return factorial(n)//(factorial(r)*factorial(n-r))


def solve():
    n,a=sint(),lst()
    l,r=0,n-1
    sl,sr=a[0],a[n-1]
    ans = 0
    while l<r :
        if sl==sr :
            ans = max(ans,n+1-r+l)
        if sl <= sr :
            l+=1
            sl+=a[l]
        elif sl > sr :
            r-=1
            sr+=a[r]
    print(ans)

def main():
    tc=1
    tc=int(input())
    for _ in range(tc):
        solve()
    stop = timeit.default_timer()
    if not ONLINE_JUDGE :
        print("Time Elapsed :" , str(stop-start) , "seconds")


def lst()->list :
    return list(map(int,input().split()))

def rowinp() :
    return map(int,input().split())

def strin()->str :
    return input()

def chlst()->list :
    return [x for x in input()]

def sint()->int :
    return int(input())


main()

C++ Code:

#include<bits/stdc++.h>
#define ll long long
using namespace std;
void solve(){

    ll n; cin>>n;
    ll a[n],c=0;
    for(int i=0;i<n;++i){
        cin>>a[i];
    }
    ll x=0,y=n-1;
    ll sa=0,sb=0,ans=0;
    while(x<=y){
        if(sa>=sb){
            sb+=a[y];
            y--;
            c++;
        }
        else
        {
            sa+=a[x];
            x++;
            c++;
        }
        if(sa==sb){
            ans=c;
        }
    }
    cout<<ans;

    cout<<endl;   
}
int main(){
    int t;cin>>t;
    //int t=1;
    while(t--){
        solve();
    }
}


Comments

Submit
0 Comments
More Questions

Teddy and Tweety
Partitioning binary strings
Special sets
Smallest chosen word
Going to office
Color the boxes
Missing numbers
Maximum sum
13 Reasons Why
Friend's Relationship
Health of a person
Divisibility
A. Movement
Numbers in a matrix
Sequences
Split houses
Divisible
Three primes
Coprimes
Cost of balloons
One String No Trouble
Help Jarvis!
Lift queries
Goki and his breakup
Ali and Helping innocent people
Book of Potion making
Duration
Birthday Party
e-maze-in
Bricks Game