#๐Ÿ”’ Harmonious Subsequence

38 messages ยท Page 1 of 1 (latest)

foggy hornet
#

We define a harmonious array as an array where the difference between its maximum value and its minimum value is exactly 1.

Given an integer array nums, return the length of its longest harmonious subsequence among all its possible subsequences.
Example 1:
Input: nums = [1,3,2,2,5,2,3,7]
Output: 5
Explanation:
The longest harmonious subsequence is [3,2,2,2,3].
Example 2:
Input: nums = [1,2,3,4]
Output: 2
Explanation:
The longest harmonious subsequences are [1,2], [2,3], and [3,4], all of which have a length of 2.

Example 3:
Input: nums = [1,1,1,1]
Output: 0

obtuse cryptBOT
#

@foggy hornet

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

foggy hornet
#

My code:

longest = []
        d = []
        prev = 0

        while prev < len(nums):
            for j in range(len(nums)):
                if nums[j] - nums[prev] == 1:
                    d = nums[prev:j]
                    if len(d) > len(longest):
                        longest =d
            prev += 1
        return len(longest) ```
#

Why is it failing test case 2?

austere trench
foggy hornet
#

Sure

fathom spear
craggy siren
#

Or just any valid sequence in any order

steel yarrow
craggy siren
steel yarrow
craggy siren
#

yep, I will, if the op still here, I am like 1h after the original post tho, I am gonna hope he is still here

foggy hornet
#

Sorry, i was solving this problem

#

I realized my approach was incorrect

foggy hornet
#

I used to sliding window + hash map to solve it, opposed to just sliding window as i did at the beginning

#

This is actually my first day of learning "sliding window" concept

#

So my first solution was far from correct

craggy siren
#

Since it isn't calculate a continuous sequence

#

There are a 5 in the middle

foggy hornet
#

New passed the test cases

craggy siren
foggy hornet
#

My output is 5

craggy siren
#

Oh, sliding window of this
That's whypithink

#

You can use sorted to make it easier potentially

foggy hornet
craggy siren
#

Well, you don't need hashmap if you sorted it
But idk if it would be faster

foggy hornet
#

Gotcha

#

Thanks

obtuse cryptBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.