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
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:
(a, b)
from the heap.(a, b)
satisfies C(a * b)
. If so, you are done.(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:
(500.000, 500.000), (500.001, 500.001), ... , (1.000.000, 1.000.000)
to the heap and find your best pair (a, b)
.(0, 0), (1, 1), ... (499.999, 499.999)
.