Highest number less than or equal to the given number.




Comment hidden because of low score. Click to expand.
0
of 0 vote

Hey Anup,

The idea described by LinhHA05 is the most optimal one. Here's some sample code:

int getHighest(vector<int> numbers, int givenNumber) {
    int bestNumber = numeric_limits<int>::min();
    
    for (int i = 0; i < numbers.size(); i++) {
        if (numbers[i] <= givenNumber && numbers[i] > bestNumber) {
            bestNumber = numbers[i];
        }
    }
    
    return bestNumber;
}

At an interview, you should be very careful with two things:
1) How should you set your initial value for bestNumber (how low can givenNumber be)?
2) What should your code return when there are no numbers smaller than or equal to givenNumber?

Also:

The solution above is optimal assuming the "getHighest" function is called only once. If you need a solution that works for multiple queries over the same set of numbers, let me know.

Cheers,

Slavi
HiredInTech

- hiredintech September 06, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

The O(n) solution is trivial, go through all element and update the maximal value less than the reference.

- LinhHA05 September 04, 2013 | Flag Reply




Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More