Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit e27c1e8

Browse files
D. J.:
- Added the leetcode problem and solution for 594
1 parent ce73b9b commit e27c1e8

File tree

3 files changed

+41
-0
lines changed

3 files changed

+41
-0
lines changed

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,7 @@
238238
- [516 Longest Palindromic Subsequence](https://leetcode.com/problems/longest-palindromic-subsequence/description/)
239239
- [518 Coin Change II](https://leetcode.com/problems/coin-change-ii/description/)
240240
- [530 Minimum Absolute Difference in BST](https://leetcode.com/problems/minimum-absolute-difference-in-bst/description/)
241+
- [594 Longest Harmonious Subsequence](https://leetcode.com/problems/longest-harmonious-subsequence/description/)
241242
- [637 Average of Levels in Binary Tree](https://leetcode.com/problems/average-of-levels-in-binary-tree/description/)
242243
- [643 Maximum Average Subarray I](https://leetcode.com/problems/maximum-average-subarray-i/description/)
243244
- [646 Maximum Length of Pair Chain](https://leetcode.com/problems/maximum-length-of-pair-chain/description/)
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import collections
2+
from typing import List
3+
4+
5+
class Solution:
6+
"""Base class for all LeetCode Problems."""
7+
8+
def findLHS(self, nums: List[int]) -> int:
9+
"""
10+
We define a harmonious array as an array where the difference between its
11+
maximum value and its minimum value is exactly 1.
12+
13+
Given an integer array nums, return the length of its longest harmonious
14+
subsequence among all its possible subsequences.
15+
"""
16+
lhs = 0
17+
count = collections.Counter(nums)
18+
for val, freq in count.items():
19+
hs = 0 if val - 1 not in count else freq + count[val - 1]
20+
lhs = max(lhs, hs)
21+
return lhs
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
from typing import List
2+
3+
import pytest
4+
5+
from awesome_python_leetcode._594_longest_harmonious_subsequence import Solution
6+
7+
8+
@pytest.mark.parametrize(
9+
argnames=["nums", "expected"],
10+
argvalues=[
11+
([1, 3, 2, 2, 5, 2, 3, 7], 5),
12+
([1, 2, 3, 4], 2),
13+
([1, 1, 1, 1], 0),
14+
],
15+
)
16+
def test_func(nums: List[int], expected: int):
17+
"""Tests the solution of a LeetCode problem."""
18+
lhs = Solution().findLHS(nums)
19+
assert lhs == expected

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /