Advertisement
Guest User

Untitled

a guest
Jun 24th, 2019
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. import math
  2. from collections import Counter
  3.  
  4. def firstgreaterthan(A, value):
  5. # returns the first index in A that is greater than value, assuming that A
  6. # is sorted ascending.
  7. l = len(A)
  8.  
  9. if l == 0:
  10. return -1e6
  11. if l == 1:
  12. if A[0] >= value:
  13. return 0
  14. else:
  15. return -1e6
  16. if l == 2:
  17. if A[0] >= value:
  18. return 0
  19. elif A[1] >= value:
  20. return 1
  21. else:
  22. return -1e6
  23. mid = l // 2
  24. if A[mid] >= value:
  25. return firstgreaterthan(A[:mid+1], value)
  26. else:
  27. return mid + firstgreaterthan(A[mid:], value)
  28.  
  29. def solution(A, X):
  30. counts = Counter()
  31. twos = set()
  32. fours = set()
  33.  
  34. for v in A:
  35. counts[v] += 1
  36.  
  37. for v in counts:
  38. if counts[v] > 1:
  39. twos.add(v)
  40. if counts[v] > 3:
  41. fours.add(v)
  42.  
  43. if not twos and not fours:
  44. return 0
  45.  
  46. pen_count = 0
  47.  
  48. lfours = list(sorted(list(fours)))
  49. sqX = math.sqrt(X)
  50.  
  51. idx = firstgreaterthan(lfours, sqX)
  52. if idx > -1:
  53. pen_count += len(lfours) - idx
  54.  
  55. ltwos = list(sorted(list(twos)))
  56. lt = len(ltwos)
  57.  
  58. if lt < 2:
  59. if pen_count > 1e9:
  60. return -1
  61. return pen_count
  62.  
  63. i = 0
  64. j = lt - 1
  65.  
  66. # count the number of pairs with product less than X.
  67. lt_count = 0
  68. while i < j:
  69. if ltwos[i] * ltwos[j] < X:
  70. lt_count += (j - i)
  71. i += 1
  72. else:
  73. j -= 1
  74.  
  75. # now subtract the number of pairs with product less than X from the total
  76. # number of pairs in ltwos.
  77. pen_count += int(len(ltwos) * (len(ltwos) - 1) * 0.5) - lt_count
  78.  
  79. if pen_count > 1e9:
  80. return -1
  81.  
  82. return pen_count
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement