Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import math
- from collections import Counter
- def firstgreaterthan(A, value):
- # returns the first index in A that is greater than value, assuming that A
- # is sorted ascending.
- l = len(A)
- if l == 0:
- return -1e6
- if l == 1:
- if A[0] >= value:
- return 0
- else:
- return -1e6
- if l == 2:
- if A[0] >= value:
- return 0
- elif A[1] >= value:
- return 1
- else:
- return -1e6
- mid = l // 2
- if A[mid] >= value:
- return firstgreaterthan(A[:mid+1], value)
- else:
- return mid + firstgreaterthan(A[mid:], value)
- def solution(A, X):
- counts = Counter()
- twos = set()
- fours = set()
- for v in A:
- counts[v] += 1
- for v in counts:
- if counts[v] > 1:
- twos.add(v)
- if counts[v] > 3:
- fours.add(v)
- if not twos and not fours:
- return 0
- pen_count = 0
- lfours = list(sorted(list(fours)))
- sqX = math.sqrt(X)
- idx = firstgreaterthan(lfours, sqX)
- if idx > -1:
- pen_count += len(lfours) - idx
- ltwos = list(sorted(list(twos)))
- lt = len(ltwos)
- if lt < 2:
- if pen_count > 1e9:
- return -1
- return pen_count
- i = 0
- j = lt - 1
- # count the number of pairs with product less than X.
- lt_count = 0
- while i < j:
- if ltwos[i] * ltwos[j] < X:
- lt_count += (j - i)
- i += 1
- else:
- j -= 1
- # now subtract the number of pairs with product less than X from the total
- # number of pairs in ltwos.
- pen_count += int(len(ltwos) * (len(ltwos) - 1) * 0.5) - lt_count
- if pen_count > 1e9:
- return -1
- return pen_count
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement