How fast is this algorithm?

Revision en4, by phsads, 2025-09-03 11:27:02

GIven this problem:

Given $$$n$$$ pairs $$$a_i$$$, $$$b_i$$$, pick $$$k$$$ of them so that $$$\frac{\sum_{}^{}a_i}{\sum_{}^{}b_i}$$$ is maximized, output the maximum value.

Constraints:

$$$1 \le k \le n \le 200000$$$

$$$a_i, b_i \le 10^{6}$$$

I have this scuffed greedy algorithm which does the following:

  1. Assume the result is $$$\ge x$$$, then let $$$u_i = a_i - xb_i$$$

  2. Greedily pick the largest $$$K$$$ values of $$$u_i$$$.

  3. Update $$$x$$$ to the new optimal value, if the new value is not better then stop.

After a lot of random tests, the worst case only made it perform $$$7$$$ iterations.

Are there any tests that makes it TLE, or at least run a lot more than $$$7$$$ iterations? If not, is there a proof? What is the runtime in the worst case?

Code

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en6 English phsads 2025-09-03 11:29:39 14
en5 English phsads 2025-09-03 11:27:20 2 Tiny change: ' largest $K$ values o' -> ' largest $k$ values o'
en4 English phsads 2025-09-03 11:27:02 7 Tiny change: 'e runtime worst ca' -> 'e runtime in the worst ca' (published)
en3 English phsads 2025-09-03 11:26:32 358
en2 English phsads 2025-09-03 11:23:55 1356
en1 English phsads 2025-09-03 11:17:52 391 Initial revision (saved to drafts)