680. The Pair Whose Product Lands Nearest
Given n positive integers and a target, choose two of them by position and make their
PRODUCT as close to the target as possible.
If two achievable products are equally close, print the SMALLER one.
1 2 3 4, target 7 -> 6 from 2 and 3
2 3 5, target 10 -> 10 exactly
1 2 3 4 5, target 11 -> 10
## The same sweep, with multiplication
Sort, converge, and keep the best product seen. The product rises as i advances and falls as
j retreats, because all the values are positive:
p < target -> i += 1 raise the product
p > target -> j -= 1 lower it
p == target -> stop, nothing is closer
This is problem 615 with the sum replaced by a product and the target moved off zero.
## Why positivity is doing the work
With positive values, replacing a[i] by a larger value strictly increases the product, and
replacing a[j] by a smaller one strictly decreases it. That monotonicity is what tells the
sweep which pointer to move.
Allow a zero or a negative and it breaks: multiplying by a larger value can decrease the product. The constraint says positive for that reason, and problem 675 needs the same promise for the same reason.
## The tie-break
The statement takes the SMALLER product on a tie, which matches problem 607 and is the opposite
of problem 615. Compare abs(p - target) first, then break equality with p < best.
Three problems in this topic ask for a nearest value and they do not all agree, deliberately. Reading the rule each time is the habit; remembering one and reusing it is the bug.
## Overflow
Two values near 10^9 multiply to 10^18, which fits in a signed 64 bit integer and not in a
double. JavaScript needs big integers, as in problem 675.
## Boundaries
Two values give one product, whatever it is. All values equal give that value squared.
## Cost
Time O(n log n) for the sort. Space O(1) beyond the input.
Constraints - `2 ≤ n ≤ 200000` - `1 ≤ each value ≤ 10^9` - `1 ≤ target ≤ 10^18`
Input
The first line contains two integers n and target.
The second line contains n positive integers.
Output
Print one integer, the achievable product nearest the target, the smaller one on a tie.
Hints
Four rungs, in order. The last two open once you have submitted an attempt. A wrong one counts.