Order (a,b) pairs by result of a*b

前端 未结 4 2014
离开以前
离开以前 2021-01-18 18:59

I would like to find the highest value m = a*b that satisfies some condition C(m), where

1 <= a <= b <= 1,000,000.

In order to do

4条回答
  •  囚心锁ツ
    2021-01-18 19:29

    Provided that C(m) is so magical that you cannot use any better technique to find your solution directly and thus you really need to traverse all a*b in decreasing order, this is what I would do:

    Initialize a max-heap with all pairs (a, b) such that a = b. This means that the heap contains (0, 0), (1, 1), ... , (1.000.000, 1.000.000). The heap should be based on the a * b value.

    Now continuously:

    1. Get the max pair (a, b) from the heap.
    2. Verify if (a, b) satisfies C(a * b). If so, you are done.
    3. Otherwise, add (a, b-1) to the heap (provided b > 0, otherwise do nothing).

    This is a very simple O(n log n) time and O(n) space algorithm, provided that you find the answer quickly (in a few iterations). This of course depends on C.


    If you run into space problems you can of course easily decrease the space complexity by splitting up the problem in a number of subproblems, for instance 2:

    1. Add only (500.000, 500.000), (500.001, 500.001), ... , (1.000.000, 1.000.000) to the heap and find your best pair (a, b).
    2. Do the same for (0, 0), (1, 1), ... (499.999, 499.999).
    3. Take the best of the two solutions.

提交回复
热议问题