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:
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
if sum(a)<sum(b):
    print(-1)
else:
    c=[0 for i in range(n)]
    for j in range(n):
        c[j]=a[j]-b[j]
    c=sorted(c,reverse=True)
    d=c.copy()
    first=0
    second=n-1
    flag=True
    while flag:
        if c[second]>=0:
            flag=False
        else:
            if c[first]>=-c[second]:
                c[first]+=c[second]
                c[second]=0
                second-=1
            elif c[first]<-c[second]:
                c[second]+=c[first]
                c[first]=0
                first+=1
    ans=0
    for k in range(n):
        if d[k]!=c[k]:
            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):
    neg = []
    pos = []
    for i in range(N):
        d = A[i]-B[i]
        if d<0:
            neg.append(-d)
        elif d>0:
            pos.append(d)
    negsum = sum(neg)
    pos.sort(reverse=True)
    possum = 0
    for i in range(len(pos)+1):
        if possum >= negsum:
            print(i+len(neg))
            break
        possum += pos[i]
else:
    print(-1)

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)])
tot = sum(C)
cnt = 0
if tot<0:
    cnt = -1
else:
    a = 0
    for i in range(N):
        if C[i]<0:
            a += C[i]
            cnt += 1
        else:
            break
    for i in range(N-1,-1,-1):
        if a>=0:break
        a += C[i]
        cnt += 1
print(cnt)

Submission status: Accepted

Solution code:
from itertools import accumulate
import bisect
n = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
C = []
ans = 0
c = 0
for i in range(n):
  d = A[i]-B[i]
  if d > 0:
    C.append(d)
  elif d < 0:
    ans += 1
    c -= d
Q = list(accumulate(sorted(C, reverse=True)))
if c == 0:
  print(0)
elif sum(A) < sum(B):
  print(-1)
else:
  t = bisect.bisect_left(Q, c)
  ans += t+1
  print(ans)

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
cnt=[]
num=0
sum=0
for i in range(n):
    q=a[i]-b[i]
    if q<0:
        num+=1
        sum-=q
    else:
        cnt.append(q)

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

else:
    res=num
    cnt.sort(reverse=True)
    p=0
    for i in range(len(cnt)):
        p+=cnt[i]
        res+=1
        if p>=sum:
            break

    if p>=sum:
        print(res)
        exit()

print(-1)

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int, input().split())) 
b=list(map(int, input().split())) 
countA=0
countA1=0
countB=0
countB1=0
v=[]
        
if sum(a)<sum(b):
    print(-1)
    exit()

for i in range(n):
    if a[i]>b[i]:
        v.append(a[i]-b[i])
    elif a[i]==b[i]:
        continue
    else:
        countA+=(b[i]-a[i])
        countA1+=1

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

v.sort()
v.reverse()

for i in range(len(v)):
    countB+=v[i]
    countB1+=1
    if countB>=countA:
        print(countA1+countB1)
        exit()

Submission status: Accepted

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

dp=[];dn=[]
for i in range(N):
    if A[i]>B[i]:
        dp.append(A[i]-B[i])
    elif A[i]<B[i]:
        dn.append(B[i]-A[i])

if sum(dn)>sum(dp):
    ans=-1
elif len(dn)==0:
    ans=0
else:
    dnsum=sum(dn)
    dp.sort(reverse=True)
    ans=len(dn)
    for dpi in dp:
        dnsum-=dpi
        ans+=1
        if dnsum<=0:
            break

print(ans)

Submission status: Accepted

Solution code:
# 2019-11-28 00:55:58(JST)
import sys
import numpy as np

def main():
    n = int(sys.stdin.readline().rstrip())
    ab = np.array(sys.stdin.read().split(), dtype=np.int64)
    a = ab[:n]
    b = ab[n:]

    res = np.sort(a - b)
    if res.sum() < 0:
        print(-1)
        sys.exit()

    negative_cnt = np.sum(res < 0)
    if not negative_cnt:
        print(0)
        sys.exit()

    negative_sum = np.sum(res[:negative_cnt])
    positive_cnt = 0
    for i in range(n-1, -1, -1):
        negative_sum += res[i]
        positive_cnt += 1
        if negative_sum >= 0:
            break
    cnt = positive_cnt + negative_cnt

    print(cnt)
    
if __name__ == '__main__':
    main()

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()
S = 0
cnt = 0
AB = []
for i in range(N):
  if A[i] >= B[i]:
    AB.append(A[i] - B[i])
  else:
    S += B[i] - A[i]
    cnt += 1
AB = sorted(AB)[::-1]
i = 0
while S > 0:
  S -= AB[i]
  cnt += 1
  i += 1
print(cnt)

Submission status: Accepted

Solution code:
import numpy as np
from collections import deque
import sys 
N=int(input())
A=np.array([int(i) for i in input().split()])
B=np.array([int(i) for i in input().split()])
C = A-B
minus_idx=np.where(C<0)
plus_idx=np.where(C>=0)
minus = np.sum(C[minus_idx])
plus = deque(np.sort(C[plus_idx]))
len_plus = len(plus)

if len(minus_idx[0]) == 0:
    print(0)
    sys.exit()
if len_plus == 0:
    print(-1)
    sys.exit()
count = 0
while minus<0:
    try:
        minus += plus.pop()
        count += 1
        len_plus -= 1
    except:
        print(-1)
        sys.exit()
print(len(minus_idx[0])+count)

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(0)
res = 0
t = 0
for i in range(N):
	if a[i] < b[i]:
		t += b[i] - a[i]
		a[i] = b[i]
		res += 1
ab = [(a[i], b[i]) for i in range(N)]
ab.sort(key = lambda x: (x[1] - x[0]))
for i in range(N):
	if t <= 0: break
	if ab[i][0] - ab[i][1] > 0:
		t -= ab[i][0] - ab[i][1]
		res += 1
print(res)

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()
diff = []
for i in range(N):
    diff.append(B[i] - A[i])
diff.sort()
s = 0
answer = 0
for x in diff:
    if x > 0:
        answer += 1
        s += x
for x in diff:
    if s <= 0:
        break
    answer += 1
    s += x  
print(answer)

Submission status: Accepted

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

ans = 0
smaller = 0
diffs = []
for i in range(N):
    if A[i] < B[i]:
        ans += 1
        smaller += B[i] - A[i]
    elif A[i] >= B[i]:
        diffs.append(A[i] - B[i])

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

diffs.sort(reverse=True)
for d in diffs:
    if smaller <= d:
        ans += 1
        smaller -= d
        break
    else:
        ans += 1
        smaller -= d
else:
    print(-1)
    exit()

print(ans)

Submission status: Accepted

Solution code:
n=int(input())
a=[int(i) for i in input().split()]
b=[int(i) for i in input().split()]
if sum(b)>sum(a):
    print(-1)
    exit()

j,k=[],[]
for i in range(n):
    if a[i]>b[i]:
        j.append(a[i]-b[i])
    elif a[i]<b[i]:
        k.append(b[i]-a[i])
ans=len(k)

j.sort()
t=sum(k)
while t>1:
    t-=j.pop()
    ans+=1
print(ans)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
import copy
import collections
from bisect import bisect_left
from bisect import bisect_right
from collections import defaultdict
from heapq import heappop, heappush, heapify
import math
import itertools
import random
 
# NO, PAY-PAY
#import numpy as np
#import statistics
#from statistics import mean, median,variance,stdev
 
INF = float('inf')
def inputInt(): return int(input())
def inputMap(): return map(int, input().split())
def inputList(): return list(map(int, input().split()))
 
def main():
    N = inputInt()
    A = inputList()
    B = inputList()
    
    A_sum = 0
    for i in A:
        A_sum += i
    
    B_sum = 0
    for i in B:
        B_sum += i
        
    if A_sum < B_sum:
        print(-1)
        sys.exit()
        
    tarinai = []
    tariteru = []
    flg = False
    for i in range(N):
        if A[i] < B[i]:
            tarinai.append(B[i] - A[i])
            tariteru.append(0)
            flg = True
        else:
            tarinai.append(0)
            tariteru.append(A[i] - B[i])
            
    if flg == False:
        print(0)
        sys.exit()
        
    tariteru.sort()
    tariteru = tariteru[::-1]
            
    ans = 0
    tameru = 0
    for i in tarinai:
        if i == 0:
            continue
        ans += 1
        tameru += i
        
    for i in tariteru:
        ans += 1
        tameru -= i
        if tameru <= 0:
            break
            
    print(ans)
    
if __name__ == "__main__":
	main()

Submission status: Accepted

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

lack = []
remain = []
for i in range(N):
    if A[i] < B[i]:
        lack.append(B[i]-A[i])
    if A[i] > B[i]:
        remain.append(A[i]-B[i])

sumlack = sum(lack)
remain.sort(reverse=True)

cnt = 0
while sumlack > 0:
    sumlack -= remain[cnt]
    cnt += 1
    if cnt == len(remain) and sumlack > 0:
        print(-1)
        exit()
        break

print(len(lack)+cnt)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
diff = [a-b for a,b in zip(A, B)]
orderdiff = sorted(diff, reverse=True)

# 浮いている分からマイナスを補填、何個使ったかを管理するためのリスト
plsdiffcnt = [0] * (N + 1)
plsdiffcnt[0] = orderdiff[0]
for i in range(len(orderdiff)-1):
  if orderdiff[i] > 0:
    plsdiffcnt[i+1] = plsdiffcnt[i] + orderdiff[i+1]

#マイナス値の合計とその個数を取得
mnscnt = 0
mnssum = 0
for i in diff:
  if i < 0:
    mnscnt += 1
    mnssum -= i
    
if all([i >= 0 for i in diff]):
  print(0)
  exit()
    
if sum(diff) < 0:
  print(-1)
  exit()
     
for i, v in enumerate(plsdiffcnt):
  if mnssum <= v:
    ans = i + 1
    break
print(mnscnt+ans)

Submission status: Accepted

Solution code:
N=int(input())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
AB=sorted([i-m for i,m in zip(A,B)])

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

data=[i for i in AB if i<0]
count=len(data)
value=sum(data)
_N=N-1

while value<0:
    value+=AB[_N]
    count+=1
    _N-=1
print(count)

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
ab=[]
ans=0
zure=0
for i in range(n):
    if a[i]<b[i]:
        ans+=1
        zure+=b[i]-a[i]
    ab.append([a[i]-b[i],a[i],b[i]])
ab.sort(key=lambda x:x[0], reverse=True)
i=0
while zure>0 and i<n:
    ans+=1
    zure-=ab[i][0]
    i+=1
if i==n:
    print(-1)
    exit()
print(ans)

Submission status: Accepted

Solution code:
#import math
#import copy
#import sys
#import bisect
#input = sys.stdin.readline
mod=10**9+7
def factorial(x): #階乗計算
    n=1
    for i in range(x):
        n=(n*(i+1))%mod
    return n

def gcd(a, b):
    if b == 0:
        return a
    else:
        return gcd(b, a%b)
def lcm(a, b):
    return((a*b)//gcd(a,b))
def div(x): #約数配列
    div=[1]
    check=2
    while(x!=1 and check <= int(x**0.5)+2):
        if(x%check==0):
            div.append(check)
            while(x%check==0):
                x=x//check
        check+=1
    if x != 1:
      div.append(x)
    return div
def div2(x): #素因数分解配列
    div2=[]
    check=2
    while(x!=1 and check <= int(x**0.5)+2):
        while x%check==0:
            div2.append(check)
            x/=check
        check+=1
    if x != 1:
      div2.append(x)
    return div2

def main():
    # x,y = map(int,input().split())           x=1,y=2
    # a = input().split()                      a=['1','2','3',...,'n']
    # a = list(map(int,input().split()))       a=[1,2,3,4,5,...,n]
    # li = input().split('T')	              FFFTFTTFF => li=['FFF', 'F', '', 'FF']
    # 複数行の「1 2 3 4」型の入力を一配列に
    # x = sorted([list(map(int, input().split())) for _ in range(n)])
    # ソート x.sort(key=lambda y:y[1])
    # [chr(i) for i in range(97, 97+26)] 英語小文字リスト
    # [chr(i) for i in range(65, 65+26)] 英語大文字リスト atcoder
    # ord(c) chr(2) alphabet <=> number
    n=int(input())
    a = list(map(int,input().split())) 
    b = list(map(int,input().split())) 
    if sum(a)<sum(b):
        print(-1)
    else:
        p=[]
        m=[]
        for i in range(n):
            if a[i]>=b[i]:
                p.append(a[i]-b[i])
            else:
                m.append(b[i]-a[i])
        if m==[]:
            print(0)
            exit()
        ans=len(m)
        debit=sum(m)
        p.sort(reverse=True)
        index=0
        while debit>0:
            debit-=p[index]
            index+=1
            ans+=1
        print(ans)
main()

Submission status: Accepted

Solution code:
def resolve():
    n = int(input())
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))
    ans = 0
    neg = 0
    pos = []
    for ai, bi in zip(a, b):
        if ai < bi:
            neg += bi - ai
            ans += 1
        else:
            pos.append(ai - bi)
    if neg > sum(pos):
        print(-1)
        return 0
    pos.sort()
    for pi in pos[::-1]:
        if neg <= 0:
            break
        neg -= pi
        ans += 1
    print(ans)


if __name__ == "__main__":
    resolve()

Submission status: Accepted

Solution code:
from sys import stdin
N = int(stdin.readline().rstrip())
A = [int(x) for x in stdin.readline().rstrip().split()]
B = [int(x) for x in stdin.readline().rstrip().split()]
diff = [A[i] - B[i] for i in range(N)]
d = [i for i in diff if i < 0]
ans = len(d)
s = sum(d)
for i in sorted(diff)[::-1]:
    if s >= 0:
        break
    s += i
    ans += 1
if sum(diff) < 0:
    ans = -1
print(ans)

Submission status: Accepted

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

AB = [(a, b) for a, b in zip(A, B)]
AB.sort(key=lambda D: D[1] - D[0])

ans = 0
plus = 0
for a, b in AB[:: -1]:
    if a - b >= 0:
        break
    plus += b - a
    ans += 1

for a, b in AB:
    if a - b <= 0 or plus <= 0:
        break
    plus -= a - b
    ans += 1

if plus > 0:
    print(-1)
else:
    print(ans)

Submission status: Accepted

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


def solve(N: int, A: "List[int]", B: "List[int]"):

    s = [0] * N
    for i in range(N):
        s[i] = A[i]-B[i]

    s.sort()
    minus = sum([i for i in s if i < 0])
    minus_len = len([i for i in s if i < 0])
    plus =  sum([i for i in s if i >= 0])

    if(minus+plus < 0):
        print(-1)
        exit()

    s.sort(reverse=True)

    ans = 0
    while minus < 0:
        minus += s[ans]
        ans += 1

    print(ans + minus_len)

    return


# Generated by 1.1.5 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    A = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    B = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    solve(N, A, B)

if __name__ == '__main__':
    main()

Submission status: Accepted

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

ng = []
po = []

if sum(A) < sum(B): print(-1)
else:
    ans = 0
    for i in range(N):
        d = A[i] - B[i]
        if d < 0:
            ans += 1
            ng.append(d)
        elif d > 0: po.append(d)
    ng.sort()
    po.sort()
    s = sum(ng)
    while po and s < 0:
        s += po.pop()
        ans += 1
    if s < 0: print(-1)
    else: print(ans)

Submission status: Accepted

Solution code:
n = int(input())
lis = list(map(int,input().split()))
li = list(map(int,input().split()))
l = [lis[i]-li[i] for i in range(n)]
l.sort()
if sum(l) < 0:
  print(-1)
  exit()
husai = 0
ans = 0
for num in l:
  if num < 0:
    ans += 1
    husai -= num
an = 0
kasan = 0
while kasan < husai:
  an += 1
  kasan += l[-an]
ans += an
print(ans)

Submission status: Accepted

Solution code:
# 2019/10/22

n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
if sum(a)<sum(b):
    print(-1)
    exit()
plus=[]
minus=[]
for aa,bb in zip(a,b):
    if aa==bb:continue
    if aa>bb:plus.append(aa-bb)
    else:minus.append(bb-aa)

plus.sort()
minus.sort(reverse=True)
p=0
m=sum(minus)
cnt=len(minus)
p=0
while p<m:
    p+=plus.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()))
c=0
d=[]
z=0
for i in range(n):
    if a[i]<b[i]:
        c+=b[i]-a[i]
    else:
        z+=1
        d.append(a[i]-b[i])
if sum(a)<sum(b):
    print(-1)
elif z==n:print(0)
else:
    d.sort()
    d=d[::-1]
    for i in range(len(d)):
        if c<=d[i]:
            print(n-(len(d)-(i+1)))
            break
        else:
            c-=d[i]

Submission status: Accepted

Solution code:
n=int(input())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
C=[]
S,ans=0,0
for a,b in zip(A,B):
    if a>=b:C.append(a-b)
    else:
        ans +=1
        S +=b-a
C.sort()
while S>0 and C:
    ans +=1
    S -=C.pop()
print(-1 if S>0 else ans)

Submission status: Accepted

Solution code:
n=int(input())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
C=[]
S,ans=0,0
for a,b in zip(A,B):
    if a>=b:C.append(a-b)
    else:
        ans +=1
        S +=b-a
C.sort()
while S>0 and C:
    ans +=1
    S -=C.pop()

print(-1 if S>0 else ans)

Submission status: Accepted

Solution code:
import heapq
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = []
for i in range(n):
    c.append(b[i]-a[i])
#print(c)
ans = 0
su = 0
for i in c:
    if (i > 0):
        ans += 1
        su += i
#print(ans, su)
heapq.heapify(c)
#print(c)
while (su > 0):
    t = heapq.heappop(c)
    if (t >= 0):
        print(-1)
        exit(0)
    su += t
    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(B) > sum(A):
    print(-1)
    exit()

remaining_power = []
for a, b in zip(A, B):
    if a > b:
        remaining_power.append(a-b)

remaining_power.sort(reverse=True)  # 余力が大きいものほど優先的に使う

need_power = 0
ans = 0
for a, b in zip(A, B):
    if b > a:
        ans += 1
        need_power += (b-a)

cnt = 0
while need_power > 0:
    need_power -= remaining_power[cnt]
    cnt += 1

print(ans+cnt)

Submission status: Accepted

Solution code:
#%%
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = [0] * n
cost = 0
ans = 0

for i in range(n):
    c[i] = a[i] - b[i]
    if c[i] < 0:
        cost -= c[i]
        ans += 1

c.sort(reverse = True)
#print(c)
s = sum(c)

#print(cost, ans)

for i in range(n):
    if cost <= 0:
        break
    else:
        cost -= c[i]
        ans += 1

if cost <= 0:
    print(ans)
else:
    print(-1)

Submission status: Accepted

Solution code:
import sys
N = int(input())
A = [int(i) for i in input().split()]
B = [int(i) for i in input().split()]
cnt = 0
M = []
ans = 0
for i in range(N):
    if B[i] > A[i]:
        cnt += B[i] - A[i]
        ans += 1
    else:
        if B[i] < A[i]:
            M.append([A[i] - B[i], i])
M.sort(reverse=True)
if cnt == 0:
    print(ans)
    sys.exit(0)
for i in range(len(M)):
    cnt -= M[i][0]
    ans += 1
    if cnt <= 0:
        print(ans)
        break
else:
    print(-1)

Submission status: Accepted

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

ok = []
S = 0
ans = 0
for a, b in zip(A, B):
    if a >= b:
        ok.append(a - b)
    else:
        ans += 1
        S += (b - a)
ok.sort()
while S > 0 and ok:
    ans += 1
    S -= ok.pop()

ans = -1 if S > 0 else ans
print(ans)

Submission status: Accepted

Solution code:
from collections import Counter,defaultdict,deque
import sys,heapq,bisect,math,itertools,string,queue
sys.setrecursionlimit(10**8)
mod = 10**9+7
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpl_str(): return list(sys.stdin.readline().split())
def inpln(n): return list(int(sys.stdin.readline()) for i in range(n))

n = inp()
a = inpl()
b = inpl()
dif = sum(a) - sum(b)
if dif < 0:
    print(-1)
else:
    m_cnt = 0
    m_num = 0
    p = []
    for i in range(n):
        if a[i] - b[i] > 0:
            p.append(a[i] - b[i])
        elif a[i] - b[i] < 0:
            m_cnt += 1
            m_num += b[i] - a[i]
    cnt = 0
    p.sort()
    while m_num > 0:
        cnt += 1
        tmp = p.pop()
        m_num -= tmp
    print(m_cnt + cnt)

Submission status: Accepted

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

ok = []
ng = 0
ans = 0
for i, j in zip(a, b):
    if i >= j:
        ok.append(i-j)
    else:
        ans += 1
        ng += j-i

ok.sort()
while ng > 0 and ok:
    ans += 1
    ng -= ok.pop()

ans = -1 if ng > 0 else ans
print(ans)

Submission status: Accepted

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


def c():
    if sum(a) < sum(b):
        return - 1

    ans = 0
    ok = []
    sum_ = 0
    for i, j in zip(a, b):
        if i >= j:
            heapq.heappush(ok, j-i)
        else:
            ans += 1
            sum_ -= i - j

    while sum_ > 0 and ok:
        ans += 1
        sum_ += heapq.heappop(ok)
    return ans


print(c())

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
 
delta = [0] * N
ans = 0
shortage = 0
for i in range(N):
	delta[i] = A[i] - B[i]
	if delta[i] < 0:
		ans += 1
		shortage += delta[i]
 
if shortage < 0:
    supply = [x for x in delta if x > 0]
    supply.sort(reverse=True)
    for i in supply:
        shortage += i
        ans += 1
        if shortage >= 0: break
 
if shortage >= 0:
	print(ans)
else:
	print(-1)

Submission status: Accepted

Solution code:
N= int(input())
A= list(map(int, input().split()))
B= list(map(int, input().split()))
s=sum(A)-sum(B)
if s<0:
    print(-1)
else:
    ans=0
    tmp=0
    C=[a-b for a,b, in zip(A,B)]
    C.sort()
    for i in C:
        if i<0:
            ans+=1
            tmp+=i
        else:
            break
    for i in C[::-1]:
        if tmp>=0:
            break
        tmp+=i
        ans+=1
    print(ans)

Submission status: Accepted

Solution code:

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

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

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

diff = []
for i in range(N):
	diff.append(A[i] - B[i])

diff.sort()
ans = 0
total = 0
for i in range(N):
	if diff[i] >= 0:
		break
	total += diff[i]
	ans += 1

for i in range(N - 1, -1, -1):
	if total < 0:
		ans += 1
		total += diff[i]
	else:
		break

print(ans)

Submission status: Accepted

Solution code:
N=int(input())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
D=[0]*N
cnt=0
S=0
for i in range(N):
    D[i]=A[i]-B[i]
    if D[i]<0:
        S-=D[i]
        cnt+=1

D.sort(reverse=True)

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


i=0
while S>0 and i<N:
    S-=D[i]
    cnt+=1
    i+=1

if i>=N:
    print(-1)
elif S<=0:
    print(cnt)

Submission status: Accepted

Solution code:
import sys
import heapq
import bisect

mod = 10**9+7
dd = ((-1,0),(1,0),(0,-1),(0,1))

def I(): return(int(sys.stdin.readline()))
def LI(): return([int(x) for x in sys.stdin.readline().split()])
def S(): return(sys.stdin.readline()[:-1])
def IR(n): return([I() for _ in range(n)])

def GCD(a,b):
    while b!=0:
        a,b = b,a%b
    return a

def LCM(a,b):
    return a * b // GCD(a,b)

def Eratosthenes(N):
    r = [True]*(N+1)
    r[0] = False
    r[1] = False
    i = 2
    while i*i<=N:
        if r[i]: 
            j = i
            while i*j<=N:
                prime[i*j]=False
                j+=1
        i+=1
    return(r)

def main():
    N = I()
    A = LI()
    B = LI()
    if sum(B)>sum(A):
        return(-1)

    ques = []
    rest = 0
    ans = 0

    for i in range(N):
        if A[i] < B[i]:
            ans += 1
            rest += B[i]-A[i]
        else:
            heapq.heappush(ques,B[i]-A[i])

    while rest>0:
        cost = heapq.heappop(ques)
        rest += cost
        ans += 1
    return(ans)

if __name__ == "__main__":
    print(main())

Submission status: Accepted

Solution code:
# keyence2019C - Exam and Wizard
def main():
    N, *AB = map(int, open(0).read().split())
    ans, shortage, pos = 0, 0, []
    for i, j in zip(AB[:N], AB[N:]):
        x = i - j
        if x >= 0:
            pos.append(x)
        else:
            ans += 1
            shortage += x
    for i in sorted(pos, reverse=1):
        if shortage >= 0:
            break
        ans += 1
        shortage += i
    flg = shortage >= 0
    print(ans if flg else -1)  # -1: shoratage still remains


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N=int(input())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
C=[A[i]-B[i] for i in range(N)]
#print(C)

C.sort()
tmp=0
cnt=0
for i in C:
  if i>=0:
    break
  tmp+=i
  cnt+=1
#print(tmp)

C.sort(reverse=True)
for i in C:
  if tmp>=0 or i<=0:
    break
  tmp+=i
  cnt+=1

print(cnt if tmp>=0 else -1)

Submission status: Accepted

Solution code:
n=int(input())
A=[int(i) for i in input().split()]
B=[int(i) for i in input().split()]
W=[]
w,l=0,0
chg=0
for i in range(n):
  a,b=A[i],B[i]
  if a>=b:
    W.append((a,b,a-b))
    w+=a-b
  else:
    l+=b-a
    chg+=1
W.sort(key=lambda x:x[2])
if l>w:
  print(-1)
else:
  while l>0:
    a,b,c=W.pop()
    l-=c
    chg+=1
  print(chg)

Submission status: Accepted

Solution code:
N = int(input())
As = list(map(int, input().split()))
Bs = list(map(int, input().split()))
#sA = sum(As)
#sB = sum(Bs)
#if sA < sB:
#  print(-1)
#  exit()
Ds1 = [Bs[i]-As[i] for i in range(N) if As[i] < Bs[i]]
Ds2 = sorted([As[i]-Bs[i] for i in range(N) if As[i] > Bs[i]], reverse=True)
#print(Ds1, Ds2)
r = len(Ds1)
d = sum(Ds1)
for D in Ds2:
  if d <= 0:
    break
  d -= D
  r += 1
if d <= 0:
  print(r)
else:
  print(-1)

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
lack=0
ob=[0]
ans=0
for i in range(n):
	if a[i]>b[i]:
		ob.append(a[i]-b[i])
	elif a[i]<b[i]:
		lack+=(b[i]-a[i])
		ans+=1
ob.sort()
ob.reverse()
for i in range(len(ob)-1):
	if lack<=0:
		break
	lack-=ob[i]
	ans+=1
	
if lack>0:
	print(-1)
else:
	print(ans)

Submission status: Accepted

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

S = 0
O = []
c = 0
for i in range(N):
    if A[i] < B[i]:
        S += B[i] - A[i]
        c += 1
    else:
        O.append(A[i]-B[i])
if c == 0:
    ok = True
if c != 0:
    O.sort(reverse=True)
    a = 0
    ok = False
    for o in O:
        a += o
        c += 1
        if a >= S:
            ok = True
            break

if ok:
    print(c)
else:
    print(-1)

Submission status: Accepted

Solution code:

def main():

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

    lack = 0
    excess = []
    ans = 0
    for i in range(N):
        if A[i] < B[i]:
            lack += B[i]-A[i]
            ans += 1
        elif A[i] > B[i]:
            excess.append(A[i]-B[i])
    excess.sort(reverse = True)
    while excess and lack > 0:
        lack -= excess.pop(0)
        ans += 1

    if lack > 0:
        return -1
    else:
        return ans


if __name__ == '__main__':
    print(main())

Submission status: Accepted

Solution code:
import heapq
N = int(input())
A = [int(i) for i in input().split()]
B = [int(i) for i in input().split()]

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

h = []
heapq.heapify(h)  # リストaのheap化

ans = 0
d = 0
for a, b in zip(A, B):
    if a >= b:
        heapq.heappush(h, -(a-b))
    else:
        ans += 1
        d += b-a

while d > 0:
    ans += 1
    d += heapq.heappop(h)

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)
    exit()


surpluses = sorted([a - b for a, b in zip(A, B) if a - b > 0])
need = [b - a for a, b in zip(A, B) if b - a > 0]
need_sum = sum(need)

ans = len(need)
tmp = 0
while tmp < need_sum:
    ans += 1
    tmp += surpluses.pop()


print(ans)

Submission status: Accepted

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

diff=[[A[i]-B[i],i] for i in range(N)]
diff=sorted(diff,key=lambda x:x[0])

idx=-1
for i in range(N):
  while(diff[i][0]<0):
    if diff[idx][0]< 0:
      print("-1")
      exit(0)
    if abs(diff[i][0]) >= diff[idx][0]:
      diff[i][0]+=diff[idx][0]
      diff[idx][0]=0
      idx-=1
    else:
      diff[idx][0]+=diff[i][0]
      diff[i][0]=0
diff=sorted(diff,key=lambda x:x[1])
C=[B[i]+diff[i][0] for i in range(N)]
ans=0
for i in range(N):
  if A[i]!=C[i]:
    ans+=1
print(ans)