Problem:


Score : 400 points

Problem Statement

A university student, Takahashi, has to take N examinations and pass all of them.
Currently, his readiness for the i-th examination is A_{i}, and according to his investigation, it is known that he needs readiness of at least B_{i} in order to pass the i-th examination.

Takahashi thinks that he may not be able to pass all the examinations, and he has decided to ask a magician, Aoki, to change the readiness for as few examinations as possible so that he can pass all of them, while not changing the total readiness.

For Takahashi, find the minimum possible number of indices i such that A_i and C_i are different, for a sequence C_1, C_2, ..., C_{N} that satisfies the following conditions:

The sum of the sequence A_1, A_2, ..., A_{N} and the sum of the sequence C_1, C_2, ..., C_{N} are equal.

For every i, B_i \leq C_i holds.

If such a sequence C_1, C_2, ..., C_{N} cannot be constructed, print -1.

Constraints

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^9

A_i and B_i are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_{N}
B_1 B_2 ... B_{N}

Output

Print the minimum possible number of indices i such that A_i and C_i are different, for a sequence C_1, C_2, ..., C_{N} that satisfies the conditions.
If such a sequence C_1, C_2, ..., C_{N} cannot be constructed, print -1.

Sample Input 1

3
2 3 5
3 4 1

Sample Output 1

3

(A_1, A_2, A_3) = (2, 3, 5) and (B_1, B_2, B_3) = (3, 4, 1). If nothing is done, he cannot pass the first and second exams.
The minimum possible number of indices i such that A_i and C_i are different, 3, is achieved when:

(C_1, C_2, C_3) = (3, 5, 2)

Sample Input 2

3
2 3 3
2 2 1

Sample Output 2

0

In this case, he has to do nothing in order to pass all the exams.

Sample Input 3

3
17 7 1
25 6 14

Sample Output 3

-1

In this case, no matter what is done, he cannot pass all the exams.

Sample Input 4

12
757232153 372327760 440075441 195848680 354974235 458054863 463477172 740174259 615762794 632963102 529866931 64991604
74164189 98239366 465611891 362739947 147060907 118867039 63189252 78303147 501410831 110823640 122948912 572905212

Sample Output 4

5



Sample input:
3
2 3 5
3 4 1


Sample output:
3

Submission status: Accepted

Solution code:
import sys
from sys import exit
from collections import deque
from bisect import bisect_left, bisect_right, insort_left, insort_right #func(リスト,値)
from heapq import heapify, heappop, heappush
from itertools import product, permutations, combinations, combinations_with_replacement
from functools import reduce
from math import sin, cos, tan, asin, acos, atan

sys.setrecursionlimit(10**6)
INF = 10**20
eps = 1.0e-20
MOD = 10**9+7

def lcm(x,y):
    return x*y//gcd(x,y)
def lgcd(l):
    return reduce(gcd,l)
def llcm(l):
    return reduce(lcm,l)
def powmod(n,i,mod):
    return pow(n,mod-1+i,mod) if i<0 else pow(n,i,mod)
def div2(x):
    return x.bit_length()
def div10(x):
    return len(str(x))-(x==0)
def perm(n,mod=None):
    ans = 1
    for i in range(1,n+1):
        ans *= i
        if mod!=None:
            ans %= mod
    return ans
def intput():
    return int(input())
def mint():
    return map(int,input().split())
def lint():
    return list(map(int,input().split()))
def ilint():
    return int(input()), list(map(int,input().split()))
def judge(x, l=['Yes', 'No']):
    print(l[0] if x else l[1])
def lprint(l, sep='\n'):
    for x in l:
        print(x, end=sep)
def ston(c, c0='a'):
    return ord(c)-ord(c0)
def ntos(x, c0='a'):
    return chr(x+ord(c0))
class counter(dict):
    def __init__(self, *args):
        super().__init__(args)
    def add(self,x):
        self.setdefault(x,0)
        self[x] += 1
class comb():
    def __init__(self, n, mod=None):
        self.l = [1]
        self.n = n
        self.mod = mod
    def get(self,k):
        l,n,mod = self.l, self.n, self.mod
        k = n-k if k>n//2 else k
        while len(l)<=k:
            i = len(l)
            l.append(l[i-1]*(n+1-i)//i if mod==None else (l[i-1]*(n+1-i)*powmod(i,-1,mod))%mod)
        return l[k]

N,A = ilint()
B = lint()
if sum(A)<sum(B):
    print(-1)
    exit()
index = list(range(N))
index.sort(reverse=True, key=lambda x:B[x]-A[x])
ans = tmp = 0
for i in index:
    if B[i]-A[i]<=0:
        break
    tmp += B[i]-A[i]
    ans += 1
for i in index[::-1]:
    if tmp==0:
        break
    tmp -= min(tmp,A[i]-B[i])
    ans += 1
print(ans)

Submission status: Accepted

Solution code:
import sys, math
from functools import lru_cache
from collections import defaultdict
from itertools import accumulate
import bisect
sys.setrecursionlimit(10**9)
MOD = 10**9+7

def input():
    return sys.stdin.readline()[:-1]

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

def ii():
    return int(input())

def i2(n):
    tmp = [list(mi()) for i in range(n)]
    return [list(i) for i in zip(*tmp)]

def main():
    N = ii()
    A = list(mi())
    B = list(mi())
    if sum(A) < sum(B):
        print(-1)
        return

    short = []
    excess = []
    for i in range(N):
        if A[i] < B[i]:
            short.append(B[i]-A[i])
        if A[i] > B[i]:
            excess.append(A[i]-B[i])
    
    if not short:
        print(0)
        return

    excess.sort(reverse=True)
    acc = list(accumulate(excess))

    k = bisect.bisect_right(acc, sum(short))

    print(len(short)+k+1)




if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from bisect import bisect_left

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

div = [a[i] - b[i] for i in range(n)]

if sum(div) < 0:
    print(-1)
    exit()

div.sort()
idx = bisect_left(div, 0)
positive = div[idx:]
negative = div[:idx]

if idx == 0:
    print(0)
    exit()

ans = len(negative)
changed = False

for x in negative:
    x = abs(x)
    while x > positive[-1]:
        x -= positive.pop(-1)
        if not changed:
            ans += 1
        changed = False
    positive[-1] -= x
    if not changed:
        ans += 1
        changed = True

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
ans = 0
s = 0
t = []
for i in range(n):
    if a[i] >= b[i]:
        t.append(a[i]-b[i])
    else:
        ans += 1
        s += b[i] - a[i]
m = len(t)
t.sort(reverse=True)
j = 0
while s > 0 and j < m:
    s -= t[j]
    j += 1
if s > 0:
    print(-1)
else:
    print(ans + j)

Submission status: Accepted

Solution code:
N=int(input())
*A,=map(int,input().split())
*B,=map(int,input().split())

if sum(A)<sum(B):
  print(-1)
  exit()
  
#A,B = map(sorted,(A,B))

res=0
count=0
for i in range(N):
  if B[i]>A[i]:
    res += B[i]-A[i]
    count += 1
    
if count==0:
  print(0)
  exit()
  
plus = [A[i]-B[i] for i in range(N) if A[i]>B[i]]
plus = sorted(plus,reverse=True)

for i in range(len(plus)):
  res -= plus[i]
  count += 1
  if res<=0:break
    
print(count)

Submission status: Accepted

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

C = [x - y for x, y in zip(A, B)]
Minus = [i for i in C if i < 0]
minus = sum(Minus)
EX = [i for i in C if i > 0]
EX.sort(reverse=True)

if sum(A) < sum(B):
    print(-1)
    exit()

i = 0
while minus < 0:
    minus += EX[i]
    i += 1

print(len(Minus) + i)

Submission status: Accepted

Solution code:
def main():
    n = int(input())
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))
    c = [0] * n
    for i in range(n):
        c[i] = a[i] - b[i]
    c.sort()
    i = 0
    j = n - 1
    cnt = 0
    tmp = c[i] + c[j]
    while i != j:
        if c[i] < 0:
            if tmp >= 0:
                cnt += 1
                i += 1
                tmp += c[i]
            else:
                cnt += 1
                j -= 1
                tmp += c[j]
        else:
            break
    if tmp >= 0:
        print(cnt + 1 if cnt > 0 else 0)
    else:
        print(-1)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys 

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

sum_C = sum(A)

if sum_C < sum(B):
    print(-1)
    sys.exit()

lack_sum = 0
surplus_sum = []
count = 0

for i in range(N):
    if B[i] > A[i]:
        lack_sum = lack_sum + (B[i] - A[i])
        count = count + 1
    elif B[i] <= A[i]:
        surplus_sum.append(A[i]-B[i])

surplus_sum = sorted(surplus_sum,reverse=True)

if len(surplus_sum) == N:
    print(0)
    sys.exit()


for j in surplus_sum:
    lack_sum = lack_sum - j
    count = count + 1

    if lack_sum <= 0:
        print(count)
        sys.exit()

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/keyence2019/tasks/keyence2019_c

import sys
# sys.setrecursionlimit(100000)
import heapq


def input():
    return sys.stdin.readline().strip()


def input_int():
    return int(input())


def input_int_list():
    return [int(i) for i in input().split()]


def main():
    n = input_int()
    A = input_int_list()
    B = input_int_list()
    plus = []
    minus = 0
    cnt = 0

    # a < b はすべて調整の必要あり
    # a < b の補填は それぞれの b > a のうち b-a が大きいところから貪欲に補填する
    for i in range(n):
        d = B[i] - A[i]
        if d > 0:
            minus += d
            cnt += 1
        else:
            heapq.heappush(plus, d)

    while minus > 0 and plus:
        minus -= -heapq.heappop(plus)
        cnt += 1

    if minus <= 0:
        print(cnt)
    else:
        print(-1)
    return


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# 13
import sys
import numpy as np


def input(): return sys.stdin.readline().strip()
def I(): return int(input())
def LI(): return list(map(int, input().split()))
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def S(): return input()
def LS(): return input().split()


INF = float('inf')


n = I()
a = np.array(LI())
b = np.array(LI())
diff = a - b
pos = [diff[i] for i in range(len(diff)) if diff[i] > 0]
neg = [diff[i] for i in range(len(diff)) if diff[i] < 0]
if sum(pos) + sum(neg) < 0:
    print(-1)
    exit()

# if len(neg) == 0:
#     print(0)
#     exit()

ans = len(neg)
s_neg = sum(neg)
sort_pos = sorted(pos)[::-1]
for elem in sort_pos:
    if s_neg < 0:
        ans += 1
        s_neg += elem
    else:
        break
print(ans)

Submission status: Accepted

Solution code:
# 13
import sys
import numpy as np


def input(): return sys.stdin.readline().strip()
def I(): return int(input())
def LI(): return list(map(int, input().split()))
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def S(): return input()
def LS(): return input().split()


INF = float('inf')


n = I()
a = np.array(LI())
b = np.array(LI())
diff = a - b
pos = [diff[i] for i in range(len(diff)) if diff[i] > 0]
neg = [diff[i] for i in range(len(diff)) if diff[i] < 0]
if sum(pos) + sum(neg) < 0:
    print(-1)
    exit()

if len(neg) == 0:
    print(0)
    exit()

ans = len(neg)
s_neg = sum(neg)
sort_pos = sorted(pos)[::-1]
for elem in sort_pos:
    if s_neg < 0:
        ans += 1
        s_neg += elem
    else:
        break
print(ans)

Submission status: Accepted

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

l = [A - B for A,B in zip(a,b)]
if sum(l) < 0:
    print(-1)
    exit()

nega = [i for i in l if i < 0]
posi = [i for i in l if i > 0]
nega.sort()
posi.sort()

p = 0
ans = 0
for n in nega:
    ans += 1
    p += n
    if p <= 0 and posi:
        # 補給
        p += posi.pop()
        ans += 1

print(ans)

Submission status: Accepted

Solution code:
N=int(input())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
C=sorted([A[i]-B[i]for i in range(N)])
if sum(C)<0:print(-1);exit()
D=[i for i in C if i<0]
m=sum(D)
i=0
while m<0:m+=C[N-i-1];i+=1
print(len(D)+i)

Submission status: Accepted

Solution code:
N=int(input())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
C=sorted([A[i]-B[i]for i in range(N)])
if sum(C)<0:
    print(-1)
else:
    D=[i for i in C if i<0]
    m=sum(D)
    i=0
    while m<0:
        m+=C[N-i-1]
        i+=1
    print(len(D)+i)

Submission status: Accepted

Solution code:
import bisect
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
C = sorted([A[i] - B[i] for i in range(N)])
if sum(C) < 0:
    print(-1)
elif min(C) >= 0:
    print(0)
else:
    D = [i for i in C if i < 0]
    m = sum(D)
    for i in range(N-1,-1,-1):
        m += C[i]
        if m >= 0:
            print(len(D)-i+N)
            break

Submission status: Accepted

Solution code:
import bisect
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
C = sorted([A[i] - B[i] for i in range(N)])
if sum(C) < 0:
    print(-1)
elif min(C) >= 0:
    print(0)
else:
    D = sorted([i for i in C if i > 0], reverse=True)
    r = [D[0]]
    for i in range(len(D)-1):
        r.append(r[i] + D[i+1])
    print(len([i for i in C if i < 0])+bisect.bisect_left(r, sum(-i for i in C if i < 0))+1)

Submission status: Accepted

Solution code:
import bisect
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
C = []
for i in range(N):
    C.append(A[i] - B[i])
C.sort()
if sum(-i for i in C if i < 0) > sum(i for i in C if i > 0):
    print(-1)
else:
    if min(C) >= 0:
        print(0)
    else:
        D = sorted([i for i in C if i > 0], reverse=True)
        r = [D[0]]
        for i in range(len(D)-1):
            r.append(r[i] + D[i+1])
        print(len([i for i in C if i < 0])+bisect.bisect_left(r, sum(-i for i in C if i < 0))+1)

Submission status: Accepted

Solution code:
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]
def input():
    return sys.stdin.readline().rstrip()
def rand_N(ran1, ran2):
    return random.randint(ran1, ran2)
def rand_List(ran1, ran2, rantime):
    return [random.randint(ran1, ran2) for i in range(rantime)]
def rand_ints_nodup(ran1, ran2, rantime):
  ns = []
  while len(ns) < rantime:
    n = random.randint(ran1, ran2)
    if not n in ns:
      ns.append(n)
  return sorted(ns)

def rand_query(ran1, ran2, rantime):
  r_query = []
  while len(r_query) < rantime:
    n_q = rand_ints_nodup(ran1, ran2, 2)
    if not n_q in r_query:
      r_query.append(n_q)
  return sorted(r_query)

from collections import defaultdict, deque, Counter
from sys import exit
from decimal import *
from heapq import heapify, heappop, heappush
from math import sqrt
from fractions import gcd
import random
import string
import copy
from itertools import combinations, permutations, product
from operator import mul, itemgetter
from functools import reduce
from bisect import bisect_left, bisect_right

import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7

#############
# Main Code #
#############
# 何番目の仕事かをレコードできる？
# 貪欲っぽい

N = getN()
A = getList()
B = getList()
plus = []
minus = []
for i in range(N):
    score = A[i] - B[i]
    if score < 0:
        minus.append(score)
    else:
        plus.append(score)
plus.sort(reverse = True)

if len(minus) == 0:
    print(0)
    exit()

cnt = sum(minus)
ans = len(minus)
for i in range(N - ans):
    cnt += plus[i]
    ans += 1
    if cnt >= 0:
        print(ans)
        exit()
print(-1)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
positive = []
negative = []
for a, b in zip(A,B):
    now = a - b
    if now > 0:
        positive.append(now)
    elif now < 0:
        negative.append(-now)
if not negative:
    print(0)
    exit()
if sum(positive) < sum(negative):
    print(-1)
    exit()
positive.sort(reverse=True)
n_sum = sum(negative)
ans = 0
for p in positive:
    ans += 1
    n_sum -= p
    if n_sum <= 0:
        break
print(ans + len(negative))

Submission status: Accepted

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

pos = []
neg = []
for i in range(n):
    d = a[i] - b[i]
    if d >= 0:
        pos.append(d)
    else:
        neg.append(-d)

pos.sort()


cnt = len(neg)
val = 0
while len(neg) > 0:
    n = neg.pop()
    while n > val:
        if len(pos) == 0:
            print(-1)
            exit()
        val += pos.pop()
        cnt += 1
    val -= n

print(cnt)

Submission status: Accepted

Solution code:
n = int(input())
alis = list(map(int, input().split()))
blis = list(map(int, input().split()))

s = 0
num = 0
for i in range(n):
    if blis[i] - alis[i] > 0:
        s += blis[i] - alis[i]
        num += 1

if num == 0:
    print(0)
    exit()

nlis = []
for i in range(n):
    if alis[i]-blis[i] >= 0:
        nlis.append(alis[i]-blis[i])

nlis.sort(reverse=True)
tmp = 0
cnt = 0
for i in nlis:
    if tmp >= s:
        break
    tmp += i
    cnt += 1

if tmp < s:
    print(-1)
else:
    print(cnt+num)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
un = 0
ov = []
ans = 0
for i in range(n):
    if a[i] < b[i]:
        un += b[i] - a[i]
        ans += 1
    elif a[i] > b[i]:
        ov.append(a[i] - b[i])
if un == 0:
    print(0)
    exit()
ov.sort(reverse = True)
for i in ov:
    un -= i
    ans += 1
    if un <= 0:
        print(ans)
        exit()
print(-1)

Submission status: Accepted

Solution code:
import bisect, copy, heapq, math, 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))
def celi(a,b):
    return -(-a//b)
sys.setrecursionlimit(5000000)
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=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))

sum_a=sum(a)
sum_b=sum(b)
if sum_a<sum_b:
    print(-1)
    exit()

lst=[]
cnt=0
ans=0
for i in range(n):
    if b[i]<=a[i]:
        lst.append(a[i]-b[i])
    else:
        cnt+=b[i]-a[i]
        ans+=1
# print(lst)
lst.sort()
# print(cnt)
# print(ans)
for i in range(len(lst))[::-1]:
    if cnt<=0:
        break
    cnt-=lst[i]
    ans+=1
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
sp=sn=0
P=[]
a=0
for i in range(n):
  d=A[i]-B[i]
  if d<0:
    sn+=d
    a+=1
  else:
    sp+=d
    P.append(d)
if sp<-sn:
  print(-1)
  exit()
for p in sorted(P)[::-1]:
  if sn>=0:
    break
  else:
    sn+=p
    a+=1
print(a)

Submission status: Accepted

Solution code:
import sys
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
num, ans, val = 0, 0, 0
vals = []

for i in range(n):
    c = b[i]-a[i]
    if c > 0:
        num += c
        ans += 1
    elif c < 0:
        vals.append(-c)
vals.sort()

if sum(a) < sum(b):
    print(-1)
else:
    for i in vals[::-1]:
        if val >= num:
            break
        ans += 1
        val += i
    print(ans)

Submission status: Accepted

Solution code:
import sys
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
num, ans, val = 0, 0, 0
vals = []

for i in range(n):
    c = b[i]-a[i]
    if c > 0:
        num += c
        ans += 1
    elif c < 0:
        vals.append(-c)
vals.sort()

if len(vals) == 0:
    print(0)
elif sum(a) < sum(b):
    print(-1)
else:
    for i in vals[::-1]:
        if val >= num:
            break
        ans += 1
        val += i
    print(ans)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split())) 
d = []

for i in range(n):
    d.append(a[i]-b[i])
d.sort()

sl = 0
ans = 0
for di in d:
    if di < 0:
        sl += di
        ans += 1
    else:
        break

if sl == 0:
    print(0)
    exit()

sr = 0
for di in reversed(d):
    if di >= 0 and sr +sl < 0:
        sr += di
        ans += 1

if sr + sl >= 0:
    print(ans)
else:
    print(-1)

Submission status: Accepted

Solution code:
def main2():
    N = int(input())
    A = [int(a) for a in input().split()]
    B = [int(b) for b in input().split()]

    if sum(A) < sum(B):
        print(-1)
    else:
        S = sum(A) - sum(B)
        C = [[a, b, b, a - b] for a, b in zip(A, B)] 
        C = sorted(C, key=lambda x:x[3])

        ans = 0
        for i in C:
            a, b, c, d = i

            if d == 0:
                pass
            
            elif d > 0:
                if d <= S:
                    S -= d
                else:
                    ans += 1
            else:
                ans += 1

        print(ans)

if __name__ == "__main__":
    main2()

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = []
cnt = 0
lack = 0

for i in range(n):
    diff = a[i] - b[i]
    if diff < 0:
        cnt += 1
        lack -= diff
    elif diff > 0:
        c.append(diff)

c = sorted(c)[::-1]

if sum(a) < sum(b):
    print(-1)
    exit()

for i in c:
    if lack <= 0:
        break
    lack -= i
    cnt += 1

print(cnt)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = []
cnt = 0
lack = 0

for i in range(n):
    if a[i] < b[i]:
        cnt += 1
        lack += b[i] - a[i]
    elif a[i] > b[i]:
        c.append(a[i] - b[i])

c = sorted(c)[::-1]
asum = sum(a)
bsum = sum(b)

if asum < bsum:
    print(-1)
    exit()
if cnt == 0:
    print(0)
    exit()

for i in c:
    lack -= i
    cnt += 1
    if lack <= 0:
        break

print(cnt)

Submission status: Accepted

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

#条件を下回っている試験は絶対変更しなくてはいけない
ans = 0
rest = 0
ex = [] #分け与えることができる準備度の負の値
heapq.heapify(ex)
for i in range(N):
    if A[i] < B[i]:
        ans += 1
        rest += B[i] - A[i]
    else:
        heapq.heappush(ex, B[i] - A[i])

pre_len = len(ex)
#print(rest)
#print(ex)
while rest > 0:
    if len(ex) <= 0:
        print(-1)
        break
    minus_rest = heapq.heappop(ex)
    rest += minus_rest
else:
    print(ans + (pre_len - len(ex)))

Submission status: Accepted

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

if sum(A) < sum(B):
    print(-1)
    exit()

minus_sum = 0
plus_list = []
ans = 0
for i in range(N):
    if A[i] < B[i]:
        minus_sum += (B[i] - A[i])
        ans += 1
    elif A[i] > B[i]:
        plus_list.append(A[i] - B[i])
plus_list.sort(reverse=True)

if minus_sum == 0:
    print(0)
    exit()

i = 0
while minus_sum > 0:
    minus_sum -= plus_list[i]
    ans += 1
    i += 1

print(ans)

Submission status: Accepted

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

surplus = []
short = 0
cnt = 0

for i in range(n):
    if a[i] > b[i]:
        surplus.append(a[i]-b[i])
    elif b[i] > a[i]:
        short += b[i]-a[i]
        cnt += 1

surplus = sorted(surplus)
s = 0

while s < short:
    if len(surplus) == 0:
        print(-1)
        exit()

    s += surplus.pop()
    cnt += 1

print(cnt)

Submission status: Accepted

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

surplus = []
short = []

for i in range(n):
    if a[i] > b[i]:
        surplus.append(a[i]-b[i])
    elif b[i] > a[i]:
        short.append(b[i]-a[i])

surplus = sorted(surplus)
taken = False
cnt = 0
for i in range(len(short)):
    cost = short.pop()
    cnt += 1

    while cost > 0:
        if len(surplus) == 0:
            print(-1)
            exit()

        take = min(cost, surplus[-1])
        cost -= take
        surplus[-1] -= take

        if not taken:
            taken = True
            cnt += 1

        if surplus[-1] == 0:
            surplus.pop()
            taken = False

print(cnt)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
if sum(a) < sum(b):
    print(-1)
else:
    d = [a[i] - b[i] for i in range(n)]
    count = 0
    num = 0
    for i in d:
        if i < 0:
            count += 1
            num += i
    d.sort(reverse = True)
    for i in d:
        if num >= 0:
            break
        num += i
        count += 1
    print(count)

Submission status: Accepted

Solution code:
import sys
import itertools
# import numpy as np
import time
import math
import heapq
from collections import defaultdict
from collections import Counter
sys.setrecursionlimit(10 ** 7)
 
INF = 10 ** 18
MOD = 10 ** 9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

# map(int, input().split())

N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
sa = sum(A)
sb = sum(B)

if sb > sa:
    print(-1)
    exit()

has_margin = []
need_point = []
for a, b in zip(A, B):
    if a == b:
        continue

    if a < b:
        need_point.append(b - a)
    else:
        has_margin.append((a - b, False))

has_margin = sorted(has_margin)
ans = len(need_point)
for x in need_point:
    while x > 0:
        y = has_margin[-1][0]
        if y >= x:
            has_margin[-1] = (y - x, True)
            x = 0
        else:
            has_margin.pop()
            x -= y
            ans += 1
if has_margin[-1][1]:
    ans += 1
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
if sum(a) < sum(b):
    print(-1)
else:
    d = [a[i] - b[i] for i in range(n)]
    count = 0
    num = 0
    for i in d:
        if i < 0:
            count += 1
            num += i
    d.sort(reverse = True)
    for i in d:
        if num >= 0:
            break
        num += i
        count += 1
    print(count)

Submission status: Accepted

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

a_sum=sum(a)
b_sum=sum(b)

if a_sum<b_sum:
    ans=-1
else:
    dif=[0]*n
    dif_sum=a_sum-b_sum
    ans=n
    for i in range(n):
        dif[i]=a[i]-b[i]
    dif.sort()
    for d in dif:
        if d>=0:
            dif_sum-=d
            if dif_sum<0:
                break
            ans-=1
    
print(ans)

Submission status: Accepted

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

X=[0]*N
minus=0
ans=0
for i in range(N):
    X[i]=A[i]-B[i]
    if X[i]<0:
        ans+=1
        minus+= X[i]

X.sort(reverse=True)
if sum(X)<0:
    ans=-1
else:
    i=0
    while minus<0:
        minus+=X[i]
        i+=1
    ans+=i

print(ans)

Submission status: Accepted

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

c=[]

for i in range(n):
    c.append(a[i]-b[i])

c=sorted(c)

i=0
minus=0
ans=0
while c[i]<0:
    minus+=c[i]
    i+=1
    ans+=1

i=n-1
plus=0
while plus+minus<0:
    if c[i]<=0:
        print(-1)
        exit(0)
    plus+=c[i]
    i-=1
    ans+=1

print(ans)

Submission status: Accepted

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

# from numba import njit

# input = stdin.readline

# @njit
def solve(n,a,b):
  delta = [b[i] - a[i] for i in range(n)]
  need = list(x for x in delta if x > 0)
  amari = list(sorted((abs(x) for x in delta if x < 0),reverse=True))
  needScore = sum(need)
  if needScore > sum(amari):
    return -1
  k = 0
  s = 0
  while s < needScore:
    s += amari[k]
    k += 1
  return k + len(need)
  


def main():
  N = int(input())
  # N,M = map(int,input().split())
  a = list(map(int,input().split()))
  b = list(map(int,input().split()))
  print(solve(N,a,b))
  return

if __name__ == '__main__':
  main()

Submission status: Accepted

Solution code:
import numpy as np
from bisect import bisect_left, bisect_right  # return index

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

if A.sum() < B.sum():
    print(-1)
    exit()

diff = A - B
diff = np.sort(diff).tolist()

zero_ix = bisect_left(diff, 0)
plus = diff[zero_ix:][::-1]
minus = diff[:zero_ix]
minus_sum = sum(minus)

cnt = len(minus)
if cnt == 0:
    print(0)
    exit()

for i in range(len(plus)):
    cnt += 1
    minus_sum += plus[i]
    if minus_sum >= 0:
        break

print(cnt)

Submission status: Accepted

Solution code:
# coding: utf-8
import collections
import bisect
#N, M = map(int,input().split())
N = int(input())
A = list(map(int,input().split()))
B = list(map(int,input().split()))
D = []
D_ = []
yoyu = 0
husoku = 0
cnt = 0
tmp = 0
for i in range(N):
    d = A[i]-B[i]
    if d > 0:
        D.append(d)
        yoyu += d
        cnt += 1
    elif d < 0:
        D_.append(abs(d))
        husoku += abs(d)
        tmp += 1
#print(yoyu, husoku)
#print(cnt, tmp)
#print(sorted(D))
if yoyu < husoku:
    print(-1)
else:
    D.sort()
    for i in range(cnt-1):
        D[i+1] += D[i]
    amari = yoyu - husoku
    #print(amari, bisect.bisect_right(D, amari))
    print(tmp + cnt - bisect.bisect_right(D, amari))

Submission status: Accepted

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

l = []
h = []

for i in range(N):
    if A[i] < B[i]:
        l.append(B[i]-A[i])
    else:
        h.append(A[i]-B[i])

h.sort()

res = 0
y = 0
for x in l:
    while x > y:
        if h:
            res += 1
            y += h.pop()
        else:
            print(-1)
            exit()
    
    res += 1
    y -= x

print(res)

Submission status: Accepted

Solution code:
import sys

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

if sum(A)<=sum(B):
    print(-1)
    sys.exit()

Y=0
K=0
Q=[]

for i in range(N):
    k=A[i]-B[i]
    if k>0:
        Q.append(k)
    elif k<0:
        K+=1
        Y+=-k

Q.sort()

while Y>0:
    q=Q.pop()
    Y-=q
    K+=1

print(K)

Submission status: Accepted

Solution code:
import sys

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

if sum(A)<=sum(B):
    print(-1)
    sys.exit()

Y=0
K=0
Q=[]

for i in range(N):
    k=A[i]-B[i]
    if k>0:
        Q.append(k)
    elif k<0:
        K+=1
        Y+=-k

Q.sort(reverse=True)

while Y>0:
    q=Q.pop(0)
    Y-=q
    K+=1

print(K)

Submission status: Accepted

Solution code:
import sys

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

if sum(A)<=sum(B):
    print(-1)
    sys.exit()

Y=0
K=0
Q=[]

for i in range(N):
    k=A[i]-B[i]
    if k>0:
        Q.append(k)
    elif k<0:
        K+=1
        Y+=-k

if Y==0:
    print(0)
    sys.exit()
    
Q.sort(reverse=True)
for q in Q:
    Y-=q
    K+=1
    if Y<=0:
        print(K)
        sys.exit()

Submission status: Accepted

Solution code:
N= int(input())
A  = list(map(int,input().split()))
B  = list(map(int,input().split()))
short = []
margine = []
for a,b in zip(A,B):
    if a > b :
        margine.append(a-b)
    elif b > a:
        short.append(b-a)
        
ss = sum(short)
sc = len(short)
margine = sorted(margine)
if ss>sum(margine):
    print(-1)
    exit()
while ss>0:
    ss -= margine.pop()
    sc += 1
print(sc)