fork download
  1. def interval(first, last):
  2. # Combine first and last into a list of tuples and sort them
  3. # Sort primarily by end point (ascending)
  4. # Sort secondarily by start point (descending) to handle subsets properly
  5. intervals = list(zip(first, last))
  6. intervals.sort(key=lambda x: (x[1], -x[0]))
  7.  
  8. ans = 0
  9. p1 = -1 # Largest element in our set
  10. p2 = -1 # Second largest element in our set
  11.  
  12. for start, end in intervals:
  13. # Case 1: The current interval already contains at least two points from our set
  14. if start <= p2:
  15. continue
  16.  
  17. # Case 2: The current interval contains exactly one point from our set
  18. if start <= p1:
  19. # We need 1 more point. Pick the largest possible point (end).
  20. # If p1 is already exactly 'end', we must pick 'end - 1'.
  21. if p1 == end:
  22. p2 = end - 1
  23. # p1 remains 'end'
  24. else:
  25. p2 = p1
  26. p1 = end
  27. ans += 1
  28.  
  29. # Case 3: The current interval contains zero points from our set
  30. else:
  31. # We need 2 points. Pick the two largest possible: 'end - 1' and 'end'
  32. p2 = end - 1
  33. p1 = end
  34. ans += 2
  35.  
  36. return ans
  37.  
  38. print(interval([3,2,0,4], [6,4,2,7]))
Success #stdin #stdout 0.13s 14176KB
stdin
Standard input is empty
stdout
4