Problem:


Score : 300 points

Problem Statement

We have two desks: A and B. Desk A has a vertical stack of N books on it, and Desk B similarly has M books on it.

It takes us A_i minutes to read the i-th book from the top on Desk A (1 \leq i \leq N), and B_i minutes to read the i-th book from the top on Desk B (1 \leq i \leq M).

Consider the following action:

Choose a desk with a book remaining, read the topmost book on that desk, and remove it from the desk.

How many books can we read at most by repeating this action so that it takes us at most K minutes in total? We ignore the time it takes to do anything other than reading.

Constraints

1 \leq N, M \leq 200000

1 \leq K \leq 10^9

1 \leq A_i, B_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M K
A_1 A_2 \ldots A_N
B_1 B_2 \ldots B_M

Output

Print an integer representing the maximum number of books that can be read.

Sample Input 1

3 4 240
60 90 120
80 150 80 150

Sample Output 1

3

In this case, it takes us 60, 90, 120 minutes to read the 1-st, 2-nd, 3-rd books from the top on Desk A, and 80, 150, 80, 150 minutes to read the 1-st, 2-nd, 3-rd, 4-th books from the top on Desk B, respectively.

We can read three books in 230 minutes, as shown below, and this is the maximum number of books we can read within 240 minutes.

Read the topmost book on Desk A in 60 minutes, and remove that book from the desk.

Read the topmost book on Desk B in 80 minutes, and remove that book from the desk.

Read the topmost book on Desk A in 90 minutes, and remove that book from the desk.

Sample Input 2

3 4 730
60 90 120
80 150 80 150

Sample Output 2

7

Sample Input 3

5 4 1
1000000000 1000000000 1000000000 1000000000 1000000000
1000000000 1000000000 1000000000 1000000000

Sample Output 3

0

Watch out for integer overflows.



Sample input:
3 4 240
60 90 120
80 150 80 150


Sample output:
3

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
n, m, k = map(int, input().split())

alist = input().split()
blist = input().split()

work = k
acount = 0
while (acount < n) and (work >= int(alist[acount])):
    work -= int(alist[acount])
    acount += 1

bCount = 0
work2 = work
while (bCount < m) and (work2 >= int(blist[bCount])):
        work2 -= int(blist[bCount])
        bCount += 1


maxCount = acount + bCount
bCount = 0
for num in range(0, acount):
    work += int(alist[acount-num-1])

    while (bCount < m) and (work >= int(blist[bCount])):
        work -= int(blist[bCount])
        bCount += 1
    maxCount = max(maxCount, acount-num-1+bCount)


print(maxCount)

Submission status: Accepted

Solution code:
N , M ,K = map(int,input().split())
A = list(map(int,input().split()))
B = list(map(int,input().split()))
if sum(A)+sum(B) <= K:
  print(N+M)
else:
  k = 0
  SB = 0
  while SB < K and k <M:
    SB += B[k]
    k += 1
  iM = k  
  k = 0
  SA = 0
  while SA < K and k < N:
    SA += A[k]
    k += 1
  if SA > K:
    k -=1
    SA -= A[k]
  km = k
  i = 0
  while i <iM:
    if SA + B[i] < K:
      SA += B[i]
      i += 1
      if km < i + k:
        km = i + k
    elif SA + B[i] == K:
      SA +=B[i]
      i += 1
      if km < i + k:
        km = i + k
    else:
      SA -= A[k - 1]
      k -= 1
  #print(SA)  
  print(km)

Submission status: Accepted

Solution code:
import sys
import os
import itertools
import numpy as np
from collections import deque

def main():
    if os.getenv("ENV")=='LOCAL':
        sys.stdin = open(os.path.dirname(__file__)+'/input.txt', 'r')

    N,M,K=map(int, input().split())
    A=list(map(int, input().split()))
    B=list(map(int, input().split()))

    lA=len(A)-1
    Ap=-1
    Bp=-1
    n=0
    t=0

    for i in range(len(A)): #Aは可能な限り足す
        if t+A[i]>K:
            break
        Ap=i
        t+=A[i]
        n+=1
    for i in range(len(B)):
        if t+B[i]>K:
            break
        Bp=i
        t+=B[i]
        n+=1

    max=n #読める本の最大値
    # print(max)
    for i in range(Ap+1):
        # print("n="+str(n)+" t="+str(t)+" A="+str(Ap)+" B="+str(Bp))
        t-=A[Ap]
        n-=1
        Ap-=1
        for j in range(Bp+1,len(B)):
            # print(str(n)+" : "+str(t)+" j="+str(j))
            if t+B[j]>K:
                break
            Bp=j
            t+=B[j]
            n+=1
        if max<n:
            max=n

    print(max)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
if __name__ == '__main__':
    n, m, k = map(int, input().strip().split())
    a = list(map(int, input().strip().split()))
    b = list(map(int, input().strip().split()))

    min = 0
    a_count = 0
    for i, a_min in enumerate(a):
        if a_min + min <= k:
            min += a_min
            a_count += 1
        else:
            break
    b_count = 0

    for i, b_min in enumerate(b):
        if b_min + min <= k:
            min += b_min
            b_count += 1
        else:
            break

    max_count = a_count + b_count
    if not max_count == n + m and not b_count == m:
        for i in a[:a_count][::-1]:
            min -= i
            a_count -= 1
            while b_count < len(b) and min + b[b_count] <= k:
                min += b[b_count]
                b_count += 1
            if a_count + b_count > max_count:
                max_count = a_count + b_count
            if b_count >= len(b):
                break
    print(max_count)

Submission status: Accepted

Solution code:
from itertools import accumulate
from bisect import bisect_left, bisect_right
import sys

input = sys.stdin.buffer.readline
n, m, k = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
AA = list(accumulate([0] + A))
BB = list(accumulate([0] + B))
apos = bisect_right(A, k)

ans = 0
for i in range(apos, -1, -1):
    temp_a = AA[i]
    remain = k - temp_a
    if remain < 0:
        continue
    pos = bisect_right(BB, remain)
    ans = max(ans, pos + i - 1)

print(ans)

Submission status: Accepted

Solution code:
N, M, K = map(int, input().split())

A = list(map(int, input().split()))
B = list(map(int, input().split()))

from collections import deque
d = deque()

buf_K = K
ans = 0
for i in range(N):
    if buf_K >= A[i]:
        buf_K -= A[i]
        d.append(A[i])
        ans += 1
    else:
        break
max_num = ans

for j in range(M):
    if buf_K >= B[j]:
        buf_K -= B[j]
        ans += 1
        if ans > max_num:
            max_num = ans
    else:
        flag = True
        while d:
            buf_K += d.pop()
            ans -= 1
            if buf_K >= B[j]:
                buf_K -= B[j]
                ans += 1
                flag = False
                break
        if flag:
            break

print(max_num)

Submission status: Accepted

Solution code:
N,M,K = list(map(int, input().split()))
A = list((map(int, input().split()))) + [10000000000]
B = list((map(int, input().split()))) + [10000000000]

S = 0
a = 0
while S+A[a]<=K:
  S+=A[a]
  a+=1

b = 0
ans = a

while a>=0:
  if S+B[b]<=K:
    S+=B[b]
    b+=1
  else:
    S-=A[a-1] 
    a-=1
  ans = max(ans, a+b)

print(ans)

Submission status: Accepted

Solution code:
import bisect
N, M, K = map(int, input().split())
bookA = list(map(int, input().split()))
bookB = list(map(int, input().split()))

sumA = [0]*(N+1)
sumB = [0]*(M+1)
maxA = N+1
for i in range(N):
    sumA[i+1] = sumA[i] + bookA[i]
    if sumA[i+1] > K:
        maxA = i+1
        break

maxB = M+1
for i in range(M):
    sumB[i+1] = sumB[i] + bookB[i]
    if sumB[i+1] > K:
        maxB = i+1
        break

pos1 = bisect.bisect_right(sumA, K, 0, maxA)-1
pos2 = bisect.bisect_right(sumB, K, 0, maxB)-1
ans = pos1
if pos2 > ans: ans = pos2
for i in range(1, maxB):
    ss = K - sumB[i]
    pos3 = bisect.bisect_right(sumA, ss, 0, maxA) + i-1
    if ans < pos3:
        ans = pos3

print(ans)

Submission status: Accepted

Solution code:
N, M, K = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
for i in range(1,N):
    A[i] += A[i-1]
for i in range(1,M):
    B[i] += B[i-1]
SA = [0] + A
SB = [0] + B
def search(rest, arr):
    l = 0
    r = len(arr)
    while (r-l) > 1:
        mid = (r+l)//2
        if arr[mid] <= rest:
            l = mid
        else:
            r = mid
    return l
ans = 0
for i in range(N+1):
    if SA[i] > K: continue
    cnt = i
    rest = K-SA[i]
    cnt += search(rest, SB)
    # print(rest, cnt, i, search(rest, SB))
    ans = max(ans, cnt)
print(ans)

Submission status: Accepted

Solution code:
import itertools
import bisect

if __name__ == "__main__":
    N, M, K = [int(x) for x in input().split(" ")]
    A = list(itertools.accumulate([int(x) for x in input().split(" ")]))
    B = list(itertools.accumulate([int(x) for x in input().split(" ")]))

    max_ = bisect.bisect_right(B, K)

    for i, a in enumerate(A):
        if K - a < 0:
            break
        j = bisect.bisect_right(B, K - a)
        max_ = max(max_, j + i + 1)
    print(max_)

Submission status: Accepted

Solution code:
#import numpy as np
import sys, math
from itertools import permutations, combinations
from collections import defaultdict, Counter, deque
from math import factorial#, gcd
from bisect import bisect_left, bisect_right #bisect_left(list, value)
sys.setrecursionlimit(10**7)
enu = enumerate
MOD = 10**9+7
def input(): return sys.stdin.readline()[:-1]
pl = lambda x: print(*x, sep='\n')

N, M, K = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))

cA = [0] + A.copy()
for i in range(N):
    cA[i+1] += cA[i]

cB = [0] + B.copy()
for i in range(M):
    cB[i+1] += cB[i]

# print(cA, cB)

maxnum = 0
# for cosA in range(0, K+1):
#     cosB = K - cosA
#     indA = bisect_left(cA, cosA)
#     indB = bisect_left(cB, cosB)
#     num = indA + indB
#     if maxnum < num: maxnum = num
# print(maxnum)
for indA, ca in enu(cA):
    if K < ca: continue
    cosB = K - ca
    indB = bisect_right(cB, cosB) - 1
    num = indA + indB
    if maxnum < num: maxnum = num
    # print(indA, indB)
print(maxnum)

Submission status: Accepted

Solution code:


import bisect
def find_le_index(a, x):
    i = bisect.bisect_right(a, x)
    if i:
        return i-1
    raise ValueError


def q3():
    n, m, k = [int(i) for i in input().split(" ")]
    A = [int(i) for i in input().split(" ")]
    B = [int(i) for i in input().split(" ")]

    asum = [0]
    s = 0
    for a in A:
        s += a
        asum.append(s)
    bsum = [0]
    s = 0
    for b in B:
        s += b
        bsum.append(s)

    maxbooks = 0
    for i in range(len(asum)):
        if k < asum[i]:
            break
        abooknum = i
        bbooknum = find_le_index(bsum, k - asum[i])
        booknum = abooknum + bbooknum
        if maxbooks < booknum:
            maxbooks = booknum

    print(maxbooks)


q3()

Submission status: Accepted

Solution code:
N, M, K = map(int,input().split())
A = list(map(int,input().split()))
B = list(map(int,input().split()))
SUM_A=[0 for _ in range(N+1)]
for i in range(N):
    SUM_A[i+1] = A[i] + SUM_A[i]
    if SUM_A[i+1] > K:
        N=i
        break

SUM_B=[0 for _ in range(M+1)]
for i in range(M):
    SUM_B[i+1] = B[i] + SUM_B[i]
    if SUM_B[i+1] > K:
        M=i
        break

cnt = N
for i in range(N+1)[::-1]:
    V=K-SUM_A[i]
    j = cnt-i
    while j < M+1 and SUM_B[j] <= V:
        j += 1
    j-=1
    if i+j > cnt:
        cnt = i+j
print(cnt)

Submission status: Accepted

Solution code:
import sys
from collections import deque
from itertools import accumulate
from bisect import bisect_right

sys.setrecursionlimit(4100000)

def main():
    N, M, K = map(int, input().split())
    A = list(map(int, input().split()))
    B = list(map(int, input().split()))
    C = [0] + list(accumulate(A))
    D = [0] + list(accumulate(B))
    if sum(A) + sum(B) <= K:
        print(N+M)
        exit()
    
    cnt = 0
    for i in range(N+1):
        tmp_cnt = i
        tmp_ans = C[i]
        if tmp_ans > K:
            break
        tmp_index = bisect_right(D, K-tmp_ans) -1
        tmp_cnt += tmp_index
        cnt = max(cnt,tmp_cnt)



    print(cnt)





if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
import numpy as np

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

N, M, K = map(int, readline().split())
AB = np.array(read().split(), np.int64)
A = AB[:N]
B = AB[N:]

Acum = np.zeros(N + 1, np.int64)
Acum[1:] = np.cumsum(A)
Bcum = np.zeros(M + 1, np.int64)
Bcum[1:] = np.cumsum(B)

Acum = Acum[Acum <= K]
Bcum = Bcum[Bcum <= K]

x = np.searchsorted(Acum, K - Bcum, side='right') - 1
x += np.arange(len(Bcum))

print(x.max())

Submission status: Accepted

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
from collections import deque

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

DR = [1, -1, 0, 0]
DC = [0, 0, 1, -1]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
     
def main():
    N, M, K = LI()
    A=  LI()
    B = LI()
    cumA = [0] * (N+1)
    cumB = [0] * (M + 1)
    for i in range(N):
        cumA[i+1] = cumA[i] + A[i]

    for j in range(M):
        cumB[j+1] = cumB[j] + B[j]

    ans = 0
    for read_a in range(N+1):
        left = K - cumA[read_a]
        if left < 0:
            continue
        if left == 0:
            ans = max(ans, read_a)
            continue
        # print('read_a: ', read_a)
        # print('cumA[read_a]: ', cumA[read_a])
        # print('left: ', left)
        # print('cumB: ', cumB)
        ix = bisect.bisect_right(cumB, left)
        # print('ix: ', ix)
        ans = max(ans, read_a + (ix - 1))
        # print()
    print(ans)

main()

Submission status: Accepted

Solution code:
from bisect import bisect_left,bisect

N, M, K = map(int, input().split())
A = list(map(int, input().split())) 
B = list(map(int, input().split()))

AR = [0]
BR = [0]

for i in range(N):
  AR.append(AR[i] + A[i])

for j in range(M):
  BR.append(BR[j] + B[j])

ans = 0

for i in range(N+1):
  if AR[i] > K:
    break
  temp = K - AR[i]
  cntB = bisect(BR, temp) - 1
  ans = max(ans, i+cntB)

print(ans)

Submission status: Accepted

Solution code:
import bisect
import copy
import heapq
import math
import sys
from collections import *
from functools import lru_cache
from itertools import accumulate, combinations, permutations, product
def input():
    return sys.stdin.readline()[:-1]
def ruiseki(lst):
    return [0]+list(accumulate(lst))
sys.setrecursionlimit(500000)
mod=pow(10,9)+7
al=[chr(ord('a') + i) for i in range(26)]
direction=[[1,0],[0,1],[-1,0],[0,-1]]

n,m,k=map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))

ans=0
now=0
# alst=[]

arui=ruiseki(a)
brui=ruiseki(b)
# print(brui)
for i in range(len(arui)):
    if arui[i]<=k:
        # print(k-arui[i])
        tmp=bisect.bisect_right(brui,k-arui[i])
        # print(tmp)
        ans=max(ans,i+tmp-1)
print(ans)

Submission status: Accepted

Solution code:
N, M, K = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))

prefix_A = [0] * (N + 1)
for i, a in enumerate(A, 1):
    prefix_A[i] = prefix_A[i - 1] + a
prefix_B = [0] * (M + 1)
for j, b in enumerate(B, 1):
    prefix_B[j] = prefix_B[j - 1] + b


res = 0
for i in range(N + 1):
    cur = prefix_A[i]
    if cur == K:
        res = max(i, res)
    elif cur < K:
        left = 0
        right = M + 1
        while right - left > 1:
            mid = (left + right) // 2
            if cur + prefix_B[mid] <= K:
                left = mid
            else:
                right = mid
        res = max(res, i + left)


print(res)

Submission status: Accepted

Solution code:
import math
#import numpy as np
import queue
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)

def main():
    n,m,k = map(int,ipt().split())
    a = [int(i) for i in ipt().split()]
    b = [int(i) for i in ipt().split()]
    an = n
    bn = m
    sm = 0
    for i,ai in enumerate(a):
        if sm+ai > k:
            an = i
            break
        sm += ai
    for i,bi in enumerate(b):
        if sm+bi > k:
            bn = i
            break
        sm += bi
    ma = an+bn
    for i in range(an):
        ai = a[an-1-i]
        sm -= ai
        for j in range(bn,m):
            if sm+b[j] > k:
                bn = j
                break
            elif j == m-1:
                bn = m
            sm += b[j]
        if ma < an-i-1+bn:
            ma = an-i-1+bn
        if bn == m:
            print(ma)
            exit()
    print(ma)


    return

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N, M, K = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
time = 0
ans_a = 0
ans_b = 0
for i in range(N):
    if time + A[i] > K:
        break
    else:
        time += A[i]
        ans_a += 1
for i in range(M):
    if time + B[i] > K:
        break
    else:
        time += B[i]
        ans_b += 1
tmp = ans_a+ans_b
tmp2 = ans_a+ans_b
cnt_b = ans_b
for i in range(ans_a):
    time -= A[ans_a-i-1]
    tmp2 -= 1
    while True:
        if cnt_b == M:
            break
        if time + B[cnt_b] > K:
            break
        else:
            time += B[cnt_b]
            cnt_b += 1
            tmp2 += 1
    tmp = max(tmp,tmp2)
print(tmp)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

import sys
# import math
# import numpy as np
# import scipy.sparse.csgraph as cs            # csgraph_from_dense(ndarray, null_value=inf), bellman_ford(G, return_predecessors=True), dijkstra, floyd_warshall
# import random                                # random, uniform, randint, randrange, shuffle, sample
# import string                                # ascii_lowercase, ascii_uppercase, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from datetime import date, datetime          # date.today(), date(year,month,day) => date obj; datetime.now(), datetime(year,month,day,hour,second,microsecond) => datetime obj; subtraction => timedelta obj
# from datetime.datetime import strptime       # strptime('2019/01/01 10:05:20', '%Y/%m/%d/ %H:%M:%S') returns datetime obj
# from datetime import timedelta               # td.days, td.seconds, td.microseconds, td.total_seconds(). abs function is also available.
# from copy import copy, deepcopy              # use deepcopy to copy multi-dimentional matrix without reference
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from fractions import Fraction               # Fraction(a, b) => a / b ∈ Q. note: Fraction(0.1) do not returns Fraciton(1, 10). Fraction('0.1') returns Fraction(1, 10)



def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79e+308
    # inf = 2 ** 63 - 1             # (for fast JIT compile in PyPy) 9.22e+18
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def isp():   return input().split()
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    

    
    n, m, k = mi()
    A = lmi()
    B = lmi()
    accum_a = [0] * (n + 1)
    accum_b = [0] * (m + 1)

    for i in range(1, n+1):
        accum_a[i] = accum_a[i-1] + A[i-1]
    for i in range(1, m+1):
        accum_b[i] = accum_b[i-1] + B[i-1]

    # print(accum_b)

    ans = 0
    for i in range(n+1):
        cnt = 0
        if accum_a[i] > k:
            break
        cnt += i
        res = k - accum_a[i]
        cnt += bisect_right(accum_b, res) - 1
        ans = max(ans, cnt)
    print(ans)



if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import bisect
N,M,K=map(int,input().split())
alist=list(map(int,input().split()))
blist=list(map(int,input().split()))

sum_alist=[0]
for i in range(N):
  sum_alist.append(sum_alist[-1]+alist[i])
#print(sum_alist)

sum_blist=[0]
for i in range(M):
  sum_blist.append(sum_blist[-1]+blist[i])
#print(sum_blist)

limit_a=bisect.bisect(sum_alist,K)
#print(limit_a)

limit_b=bisect.bisect(sum_blist,K)
#print(limit_b)

answer=0
for i in reversed(range(1,limit_a)):
  a_sum=sum_alist[i]
  b_sum=K-a_sum
  pos_b=bisect.bisect(sum_blist,b_sum)
  #print(i,pos_b-1,a_sum,sum_blist[pos_b-1],b_sum)
  answer=max(answer,i+pos_b-1)

for i in reversed(range(1,limit_b)):
  b_sum=sum_blist[i]
  a_sum=K-b_sum
  pos_a=bisect.bisect(sum_alist,a_sum)
  #print(i,pos_b-1,a_sum,sum_blist[pos_b-1],b_sum)
  answer=max(answer,i+pos_a-1)
  
if limit_a==1:
  pos_b=bisect.bisect(sum_blist,K)
  answer=pos_b-1
elif limit_b==1:
  pos_a=bisect.bisect(sum_alist,K)
  answer=pos_a-1
  
print(answer)

Submission status: Accepted

Solution code:
import numpy as np
from bisect import bisect_right
def main():
    n, m, k = list(map(int, input().split()))
    A = np.array([0, ] + list(map(int, input().split())))
    B = np.array([0, ] + list(map(int, input().split())))
    A = np.cumsum(A)
    B = np.cumsum(B)
    ans = 0
    for i in range(n + 1):
        if A[i] > k:
            break
        j = bisect_right(B, k - A[i])
        ans = max(ans, i + j - 1)
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
'''
    Auther: ghoshashis545 Ashis Ghosh
    College: jalpaiguri Govt Enggineering College

'''
from os import path
import sys
from functools import cmp_to_key as ctk
from collections import deque,defaultdict as dd 
from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
from itertools import permutations
from datetime import datetime
from math import ceil,sqrt,log,gcd
def ii():return int(input())
def si():return input()
def mi():return map(int,input().split())
def li():return list(mi())
abc='abcdefghijklmnopqrstuvwxyz'
mod=1000000007
#mod=998244353
inf = float("inf")
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]

def bo(i):
    return ord(i)-ord('a')




    
    
def solve():
    
    # for _ in range(ii()):
    n,m,k=mi()
    a=li()
    b=li()
    a1=a[:]
    b1=b[:]
    for i in range(1,n):
        a[i]+=a[i-1]
    for i in range(1,m):
        b[i]+=b[i-1]
    # print(a,b)
    i=0
    j=0
    # print(a,b)
    x1,y1=0,0
    while(k>0):
        x=bisect_right(a,k+x1,i,n)-1
        y=bisect_right(b,k+y1,j,m)-1
        if((x-i)>=(y-j)):
            if(k<a1[i]):
                break
            k-=a1[i]
            x1+=a1[i]
            i+=1
        else:
            if(k<b1[j]):
                break
            k-=b1[j]
            y1+=b1[j]
            j+=1
    print(i+j)

    
    
    
    
    
    
    
    
    
    
        
        
        
        
if __name__ =="__main__":

    if path.exists('input.txt'):
        sys.stdin=open('input.txt', 'r')
        sys.stdout=open('output.txt','w')
    else:
    	input=sys.stdin.readline
    solve()

Submission status: Accepted

Solution code:
n, m, k = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
cum_a = [0] * (n + 1)
for i, v in enumerate(a):
    cum_a[i + 1] = cum_a[i] + a[i]
cum_b = [0] * (m + 1)
for i, v in enumerate(b):
    cum_b[i + 1] = cum_b[i] + b[i]

a_idx = n
b_idx = 0
res = 0
for i in range(n + 1):
    current_a_idx = a_idx - i
    sum_a = cum_a[current_a_idx]
    if sum_a > k:
        continue
    sum_b = cum_b[b_idx]
    while sum_a + sum_b <= k and b_idx < m:
        b_idx += 1
        sum_b = cum_b[b_idx]
        if sum_a + sum_b > k:
            b_idx -= 1
            break
    res = max(b_idx + current_a_idx, res)
a_idx = 0
b_idx = m
for i in range(m + 1):
    current_b_idx = b_idx - i
    sum_b = cum_b[current_b_idx]
    if sum_b > k:
        continue
    sum_a = cum_a[a_idx]
    while sum_a + sum_b <= k and a_idx < n:
        a_idx += 1
        sum_a = cum_a[a_idx]
        if sum_a + sum_b > k:
            a_idx -= 1
            break
    res = max(current_b_idx + a_idx, res)

print(res)

Submission status: Accepted

Solution code:
from bisect import bisect
from collections import deque

N,M,K = map(int,input().split())
A = list(map(int,input().split()))
B = list(map(int,input().split()))

csumA = [0]
csumB = [0]

s = 0
for i in A:
    s += i
    csumA.append(s)
s = 0
for i in B:
    s += i
    csumB.append(s)

ans = 0
for i in range(N+1):
    if K - csumA[i] >= 0:
        ##print(i,i+bisect(csumB,max(0,K-csumA[i])))
        ans = max(ans,i-1+bisect(csumB,max(0,K-csumA[i])))

for i in range(M+1):
    if K - csumB[i] >= 0:
        ans = max(ans,i-1+bisect(csumA,max(0,K-csumB[i])))

print(ans)

Submission status: Accepted

Solution code:
from itertools import accumulate 

n,m,k=map(int,input().split())
alst=list(accumulate(list(map(int,input().split()))))
blst=list(accumulate(list(map(int,input().split()))))
#print(alst)
#print(blst)

mx=0
for i in range(len(blst)-1,-1,-1):
    if blst[i]<=k : mx=i+1;break

for i in range(len(alst)):
#    print(i,mx)
    work=k-alst[i]
    if work<0 : break
    if i+1>=mx :
        for j in range(len(blst)):
            if blst[j]>work : mx=i+1+j;break
        else : mx=i+1+len(blst)
    else:
        if work<=blst[mx-i-2]: continue
        for j in range(mx-i-1,len(blst)):
            if blst[j]>work : mx=i+1+j;break
        else : mx=i+1+len(blst)

print(mx)

Submission status: Accepted

Solution code:
import sys
from collections import deque
def input(): return sys.stdin.readline().strip()


def main():
    N, M, K = map(int, input().split())
    A = deque(map(int, input().split()))
    B = deque(map(int, input().split()))
    time = 0
    idxA = N
    idxB = M

    time = 0
    for i in range(N):
        time += A[i]
        if time > K:
            idxA = i
            break
    if time > K: time -= A[idxA]
    for j in range(M):
        time += B[j]
        if time > K:
            idxB = j
            break
    if time > K: time -= B[idxB]

    if idxA == N and idxB == M:
        print(N + M)
        return

    ans = idxA + idxB
    for i in range(idxA - 1, -1, -1):
        time -= A[i]
        while time <= K and idxB < M:
            time += B[idxB]
            idxB += 1
        if time > K:
            idxB -= 1
            time -= B[idxB]
        #print(i, idxB)
        ans = max(ans, i + idxB)
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n,m,k=map(int,input().split())
a = list(map(int,input().split()))
b = list(map(int,input().split()))

ans = 0

sum_a = sum(a)
a_max = -1

for i in range(n)[::-1]:
    if sum_a <= k:
        a_max = i
        break
    else:
        sum_a -= a[i]

ans = a_max + 1

k_dis = max(0,k-sum_a)
i1 = 0

while k_dis >= b[i1]:
    k_dis -= b[i1]
    ans += 1
    i1 += 1
    if i1 > m-1:
        break 

ans1 = ans

if i1 < m-1:
    for i in range(a_max+1)[::-1]:
        k_dis += a[i]
        ans1 -= 1
        while i1 <= m-1 and k_dis >= b[i1]:
            k_dis -= b[i1]
            ans1 += 1
            i1 += 1
            if i1 > m-1:
                break
        ans = max(ans,ans1) 

print(ans)