oneby7

1-D Dynamic Programming Increasing subsequences

532. Longest Bitonic Subsequence

Medium

You are given an array of integers nums. Return the length of its longest bitonic subsequence.

A subsequence keeps some of the elements, in their original order, and drops the rest. The kept elements do not have to be next to each other.

A subsequence is bitonic when it first strictly increases and then strictly decreases. Each element is bigger than the one before it up to the largest element, and after that each element is smaller than the one before it. Either part may be empty, so a strictly increasing or a strictly decreasing subsequence is bitonic too. Two equal values are never next to each other in it.

Example 1

Input: nums = [2, 9, 1, 3, 4, 5, 0]

Output: 5

Explanation: One longest bitonic subsequence is 2, 3, 4, 5, 0. It rises to 5 and then falls to 0. Rising to the largest value, 9, gives only 2, 9, 1, 0.

Example 2

Input: nums = [10, 4, -3, -8]

Output: 4

Explanation: The whole array falls. Its rising part is empty, which is allowed.

Example 3

Input: nums = [-7, 2, 2, -7, -9]

Output: 4

Explanation: The subsequence -7, 2, -7, -9 rises to 2 and then falls. Only one of the two 2s can be kept. The two -7s are both kept, one before the 2 and one after it.

Check your understanding

Work out the answer for this input before you write any code.

nums = [4, 8, 8, 8, 5, 1]

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.