Skip to the content

The longest climb

Problem

Write a function that takes a list of numbers and returns how many numbers the longest climb you can build out of them has.

A climb is a group of numbers you pick from the list without changing their order, and where each one is bigger than the one before it. The important part: they do not have to sit next to each other in the list, you can skip the ones that get in the way.

Look at the list 3, 10, 2, 1, 20. If only numbers that sit side by side counted, the best you could do is 3 and 10: two. But you skip the 2 and the 1, and you are left with 3, 10 and 20: three numbers, each one bigger than the one before and in the same order they appear in. That is why the answer is 3, even though those three do not sit next to each other.

The rules: "bigger" means really bigger, so two equal numbers do not carry the climb on. With a single number the answer is 1, and with an empty list it is 0.

A hint: walk the list and, for each number, look at all the earlier ones that are smaller. The longest climb that ended at one of them, plus this number, is the longest climb that ends here. Keep saving that result in another list so you do not work it out twice.

Examples

  • Up and down

    [10, 22, 9, 33, 21, 50, 41, 60] → 5

  • Three that are not side by side

    [3, 10, 2, 1, 20] → 3

  • The biggest one first

    [50, 3, 10, 7, 40, 80] → 4

  • Already in order

    [1, 2, 3, 4, 5] → 5

  • Biggest to smallest

    [9, 7, 5, 3] → 1

Besides these, the challenge has hidden tests that are revealed when you submit your solution.

You start with this

Python

def longest_climb(nums):
    pass

JavaScript

function longestClimb(nums) {
}
Solve this challenge

It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.

More O(n²) challenges

See all challenges →