[
sort
greeedy
]
BinarySearch 0266 Buying Cars
Problem statement
https://binarysearch.com/problems/Buying-Cars/
Solution
Just sort cars and choose the smalles ones.
Complexity
It is O(n log n) for time and O(1) for additional space.
Code
class Solution:
def solve(self, P, k):
P = sorted(P)
ans = 0
for i in range(len(P)):
if P[i] <= k:
ans += 1
k -= P[i]
else:
return ans
return ans
Remark
There is also O(n) time complexity solutoin, using binary search + quick algorithm for k-th order statistics - either O(n) worst time median of medians or O(n) average quickselect.