Skip to content

Commit c25eeb6

Browse files
committed
Sync LeetCode submission Runtime - 19 ms (89.80%), Memory - 19.2 MB (46.65%)
1 parent 40e5d52 commit c25eeb6

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
<p>We define a harmonious array as an array where the difference between its maximum value and its minimum value is <b>exactly</b> <code>1</code>.</p>
2+
3+
<p>Given an integer array <code>nums</code>, return the length of its longest harmonious <span data-keyword="subsequence-array">subsequence</span> among all its possible subsequences.</p>
4+
5+
<p>&nbsp;</p>
6+
<p><strong class="example">Example 1:</strong></p>
7+
8+
<div class="example-block">
9+
<p><strong>Input:</strong> <span class="example-io">nums = [1,3,2,2,5,2,3,7]</span></p>
10+
11+
<p><strong>Output:</strong> <span class="example-io">5</span></p>
12+
13+
<p><strong>Explanation:</strong></p>
14+
15+
<p>The longest harmonious subsequence is <code>[3,2,2,2,3]</code>.</p>
16+
</div>
17+
18+
<p><strong class="example">Example 2:</strong></p>
19+
20+
<div class="example-block">
21+
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4]</span></p>
22+
23+
<p><strong>Output:</strong> <span class="example-io">2</span></p>
24+
25+
<p><strong>Explanation:</strong></p>
26+
27+
<p>The longest harmonious subsequences are <code>[1,2]</code>, <code>[2,3]</code>, and <code>[3,4]</code>, all of which have a length of 2.</p>
28+
</div>
29+
30+
<p><strong class="example">Example 3:</strong></p>
31+
32+
<div class="example-block">
33+
<p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,1]</span></p>
34+
35+
<p><strong>Output:</strong> <span class="example-io">0</span></p>
36+
37+
<p><strong>Explanation:</strong></p>
38+
39+
<p>No harmonic subsequence exists.</p>
40+
</div>
41+
42+
<p>&nbsp;</p>
43+
<p><strong>Constraints:</strong></p>
44+
45+
<ul>
46+
<li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>4</sup></code></li>
47+
<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>
48+
</ul>
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# Approach: Counter
2+
3+
# Time: O(n)
4+
# Space: O(n)
5+
6+
from collections import Counter
7+
8+
class Solution:
9+
def findLHS(self, nums: List[int]) -> int:
10+
freq = Counter(nums)
11+
max_length = 0
12+
13+
for num in freq:
14+
if num + 1 in freq:
15+
max_length = max(max_length, freq[num] + freq[num + 1])
16+
17+
return max_length
18+

0 commit comments

Comments
 (0)