3 ms·
Another way to do it, assuming that the list can be mutated: find the largest number in the array, store it somewhere and remove it from the list. Do this a sec
by Luyt 12y ago
Another way to do it, assuming that the list can be mutated: find the largest number in the array, store it somewhere and remove it from the list. Do this a second time. Then add those two numbers.
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
- mden 12y agoFyi, there's a mistake in your second solution - consider a strictly increasing list.
- Luyt 12y agoThanks for the tip! 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