[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.

Source: Internet
Author: User

[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



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.