They simply flat-out could not program. Full stop.
They simply flat-out could not program. Full stop.
List<int> blah = new List<int> { 3, 8, 2, 1, 5, 9, 0, 12, 14 };
// pretend I don't know the numbers :)
blah.Sort();
blah.Reverse();
return blah[0] + blah[1]; int sum = blah.OrderByDescending(x => x).Take(2).Sum();- Do you see any problem with your method ?
- If yes (you should say yes), how can you improve it ?
In other words: the real point of asking technical questions is not can you code but much more can you engineer a solution to a problem.
return blah[blah.size()-1] + blah[blah.size()-2];
I totally would not hire you. :PI'd follow up by asking whether there's another way you could have done this (the obvious loop and store method); if you didn't come up with it, I'd explain it to you, paying attention to how well you seemed to understand it. I'd go on to ask about what characteristics make one of those solutions better than the other, hoping you'll mention the performance characteristics of sort vs. simple iteration, and maybe also the maintainability/extensibility of the two methods.
And then I'd move on to my next question with cautious hope.
It evades sorting the array, but you have to search it twice.
a = [7, 9, 2, 8]
highest = max(a)
a.remove(highest)
nexthighest = max(a)
a.remove(nexthighest)
print highest + nexthighest
Optimisation: just scan the array once, and keep track of the two highest numbers. a = [7, 9, 2, 8]
highest = None
nexthighest = None
for item in a:
if not highest or item > highest:
highest = item
elif not nexthighest or item > nexthighest:
nexthighest = item
print highest + nexthighest a = [2, 7, 8, 9]
highest = nexthighest = None
for item in a:
if not highest:
highest = item
elif item > highest:
nexthighest = highest
highest = item
elif not nexthighest:
nexthighest = item
elif item > nexthighest:
nexthighest = item
print highest + nexthighest Prelude> import Data.List
Prelude Data.List> sum . take 2 . reverse . sort $ [1..5]
9 a = [7, 9, 2, 8]
print sum(sorted(a)[-2:]) >>> print sum(sorted([])[-2:])
0