[Classic Interview Questions] [Baidu] finds the largest element C in the Set S of N positive integers, which must satisfy the requirements of C = A + B.
[Question] Find the largest element C in the Set S of N positive integers to satisfy the requirements of C = A + B. where A and B are elements in the Set S, please provide the algorithm description, code and time complexity analysis.
[Analysis]
1. Sort the set S (FAST), from small to large
2. Let C point to the last element (maximum element) of the Set)
3. Let I point to the first element in S and let j point to the previous element of C.
4. If A [I] + A [j] = C, return C;
5. if (A [I] + A [j] <C), then I ++;
6. if (A [I] + A [j]> C), then j --;
7. If the direct path I> = j still does not find any qualified element, C moves one forward in S and jumps to step 3.
[Code]
/********************************** Date: * Author: SJF0115 * Subject: In the S of A set of N positive integers, find the largest element C that satisfies C = A + B, where, B is a collection of elements in S * Source: Baidu * blog: * *********************************/# include <iostream> # include <algorithm> using namespace std; int FindSum (int A [], int n) {// sort (A, A + n); int left, right, sum; // I = C for (int I = n-1; I> = 2; -- I) {left = 0, right = I-1; // determine whether A + B = I while (left <right) {sum = A [left] + A [right]; if (sum = A [I]) {return A [I] ;}// if else if (sum> A [I]) {-- right;} else {++ left ;}} // while} // for return-1;} int main () {int A [] = {100,}; int n = 9; cout <FindSum (A, n) <endl; return 0 ;}
Discussion: [Baidu] finds the largest element C in the Set S of N positive integers, satisfying the condition that C = A + B