Topic Description:
Enter an incrementally sorted array and a number s, look for two numbers in the array, yes their and exactly is S, if there are multiple pairs of numbers and equals s, the product of the output of two numbers is the smallest.
Input:
Each test case consists of two lines:
The first line contains an integer n and k,n representing the number of elements in the array, and K represents the sum of two numbers. where 1 <= n <= 10^6,k as int
The second row contains n integers and each array is of type int.
Output:
corresponding to each test case, output two number, small first output. If it is not found, the output "1-1"
Sample input:
6
1 2 4 7 11 15
Sample output:
4 11
idea :
The most straightforward approach is violence, two for loops, Time complexity O (n*n), but this does not take full advantage of the premise of ascending arrays. Let's assume that the array is a, Len, given sum, the best way is to add the first number of the array A[low] and the last number A[high] to see if it equals sum, and if it equals sum, find a set of numbers, return true, if greater than sum, The larger number is moved forward by one bit, that is, the high--, which is added to the first and penultimate number, and if less than sum, moves the smaller number backward by one bit, that is, the low++, which becomes the second and last number added, and so on, if low== Returns False if a group of sum is not found or set at high. The time complexity of the algorithm is O (n), and the space complexity is O (1).
For this method, some proofs are required to prove the following:
For an ascending sequence a1,a2,... Ak k>=3, if A1+ak is greater than sum, then investigate the number of k-1 and A1+ak,a2+ak,... Ak-1+ak have sum<a1+ak<=a2+ak<=,... <=ak-1+ak, that is to say, AK and the number of other numbers in the series can not equal sum, so the number of abandoned AK, the result has no effect. A1+ak if it is less than sum, the same discard A1 this number has no effect on the result.
This method is suitable for any array of integers, in addition, to output the smallest group of products, there is no need to save all the results, we are very familiar with the following mathematical formula in high school to prove that the leftmost and the rightmost two of the required number of the product is the smallest.
When a+b = C, ab<= (a+b) squared/4, when and only when A==b, AB gets the maximum value, the farther the difference, the smaller the product.