Skip to content

Commit 2632274

Browse files
committed
D. J.:
- Added the Leetcode problems and solutions for 354, 646, 1027, 1218, and 1964
1 parent 0e1fbcd commit 2632274

11 files changed

+281
-0
lines changed

README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,7 @@ This repository contains awesome LeetCode problems and solutions written in Pyth
206206
- [309 Best Time to Buy and Sell Stock with Cooldown](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/description/)
207207
- [322 Coin Change](https://leetcode.com/problems/coin-change/description/)
208208
- [337 House Robber III](https://leetcode.com/problems/house-robber-iii/description/)
209+
- [354 Russian Doll Envelopes](https://leetcode.com/problems/russian-doll-envelopes/description/)
209210
- [373 Find K Pairs with Smallest Sums](https://leetcode.com/problems/find-k-pairs-with-smallest-sums/description/)
210211
- [377 Combination Sum IV](https://leetcode.com/problems/combination-sum-iv/description/)
211212
- [380 Insert Delete GetRandom O(1)](https://leetcode.com/problems/insert-delete-getrandom-o1/description/)
@@ -222,6 +223,7 @@ This repository contains awesome LeetCode problems and solutions written in Pyth
222223
- [518 Coin Change II](https://leetcode.com/problems/coin-change-ii/description/)
223224
- [530 Minimum Absolute Difference in BST](https://leetcode.com/problems/minimum-absolute-difference-in-bst/description/)
224225
- [637 Average of Levels in Binary Tree](https://leetcode.com/problems/average-of-levels-in-binary-tree/description/)
226+
- [646 Maximum Length of Pair Chain](https://leetcode.com/problems/maximum-length-of-pair-chain/description/)
225227
- [673 Number of Longest Increasing Subsequence](https://leetcode.com/problems/number-of-longest-increasing-subsequence/description/)
226228
- [712 Minimum ASCII Delete Sum for Two Strings](https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/description/)
227229
- [714 Best Time to Buy and Sell Stock with Transaction Fee](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/description/)
@@ -232,12 +234,15 @@ This repository contains awesome LeetCode problems and solutions written in Pyth
232234
- [918 Maximum Sum Circular Subarray](https://leetcode.com/problems/maximum-sum-circular-subarray/description/)
233235
- [931 Minimum Falling Path Sum](https://leetcode.com/problems/minimum-falling-path-sum/description/)
234236
- [983 Minimum Cost for Tickets](https://leetcode.com/problems/minimum-cost-for-tickets/description/)
237+
- [1027 Longest Arithmetic Subsequence](https://leetcode.com/problems/longest-arithmetic-subsequence/description/)
235238
- [1035 Uncrossed Lines](https://leetcode.com/problems/uncrossed-lines/description/)
236239
- [1137 N-th Tribonacci Number](https://leetcode.com/problems/n-th-tribonacci-number/description/)
237240
- [1143 Longest Common Subsequence](https://leetcode.com/problems/longest-common-subsequence/description/)
241+
- [1218 Longest Arithmetic Subsequence of Given Difference](https://leetcode.com/problems/longest-arithmetic-subsequence-of-given-difference/description/)
238242
- [1312 Minimum Insertion Steps to Make a String Palindrome](https://leetcode.com/problems/minimum-insertion-steps-to-make-a-string-palindrome/description/)
239243
- [1534 Count Good Triplets](https://leetcode.com/problems/count-good-triplets/description)
240244
- [1922 Count Good Numbers](https://leetcode.com/problems/count-good-numbers/description/)
245+
- [1964 Find the Longest Valid Obstacle Course at Each Position](https://leetcode.com/problems/find-the-longest-valid-obstacle-course-at-each-position/description/)
241246
- [2140 Solving Questions With Brainpower](https://leetcode.com/problems/solving-questions-with-brainpower/description/)
242247
- [2466 Count Ways To Build Good Strings](https://leetcode.com/problems/count-ways-to-build-good-strings/description/)
243248

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import collections
2+
from typing import List
3+
4+
5+
class Solution:
6+
"""Base class for all LeetCode Problems."""
7+
8+
def longestArithSeqLength(self, nums: List[int]) -> int:
9+
"""
10+
Given an array nums of integers, return the length of the longest arithmetic
11+
subsequence in nums.
12+
13+
Note that:
14+
- A subsequence is an array that can be derived from another array by deleting
15+
some or no elements without changing the order of the remaining elements.
16+
- A sequence seq is arithmetic if seq[i + 1] - seq[i] are all the same value
17+
(for 0 <= i < seq.length - 1).
18+
"""
19+
dp = [collections.defaultdict(int) for _ in range(len(nums))]
20+
for i in range(len(nums) - 2, -1, -1):
21+
for j in range(i + 1, len(nums)):
22+
diff = nums[j] - nums[i]
23+
dp[i][diff] = max(dp[i][diff], 1 + dp[j][diff])
24+
return 1 + max([max(dp_i.values()) for dp_i in dp])
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
"""Base class for all LeetCode Problems."""
6+
7+
def longestSubsequence(self, arr: List[int], difference: int) -> int:
8+
"""
9+
Given an integer array arr and an integer difference, return the length of the
10+
longest subsequence in arr which is an arithmetic sequence such that the
11+
difference between adjacent elements in the subsequence equals difference.
12+
13+
A subsequence is a sequence that can be derived from arr by deleting some or no
14+
elements without changing the order of the remaining elements.
15+
"""
16+
dp = {}
17+
result = 0
18+
for i in range(len(arr)):
19+
if arr[i] - difference in dp:
20+
dp[arr[i]] = dp[arr[i] - difference] + 1
21+
else:
22+
dp[arr[i]] = 1
23+
result = max(result, dp[arr[i]])
24+
return result
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import bisect
2+
from typing import List
3+
4+
5+
class Solution:
6+
"""Base class for all LeetCode Problems."""
7+
8+
def longestObstacleCourseAtEachPosition(self, obstacles: List[int]) -> List[int]:
9+
"""
10+
You want to build some obstacle courses. You are given a 0-indexed integer array
11+
obstacles of length n, where obstacles[i] describes the height of the ith
12+
obstacle.
13+
14+
For every index i between 0 and n - 1 (inclusive), find the length of the
15+
longest obstacle course in obstacles such that:
16+
- You choose any number of obstacles between 0 and i inclusive.
17+
- You must include the ith obstacle in the course.
18+
- You must put the chosen obstacles in the same order as they appear in
19+
obstacles.
20+
- Every obstacle (except the first) is taller than or the same height as the
21+
obstacle immediately before it.
22+
23+
Return an array ans of length n, where ans[i] is the length of the longest
24+
obstacle course for index i as described above.
25+
"""
26+
results = []
27+
dp = [float("inf") for _ in range(len(obstacles) + 1)]
28+
for k in range(len(obstacles)):
29+
i = bisect.bisect(dp, obstacles[k])
30+
results.append(i + 1)
31+
dp[i] = obstacles[k]
32+
return results
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import bisect
2+
from typing import List
3+
4+
5+
class Solution:
6+
"""Base class for all LeetCode Problems."""
7+
8+
def maxEnvelopesBS(self, envelopes: List[List[int]]) -> int:
9+
"""
10+
You are given a 2D array of integers envelopes where envelopes[i] = [wi, hi]
11+
represents the width and the height of an envelope.
12+
13+
One envelope can fit into another if and only if both the width and height of
14+
one envelope are greater than the other envelope's width and height.
15+
16+
Return the maximum number of envelopes you can Russian doll (i.e., put one
17+
inside the other).
18+
19+
Note: You cannot rotate an envelope.
20+
"""
21+
# BS Solution: O(n log n)
22+
envelopes = sorted(envelopes, key=lambda x: (x[0], -x[1]))
23+
seq = [envelopes[0]]
24+
for k in range(1, len(envelopes)):
25+
if envelopes[k][1] > seq[-1][1]:
26+
seq.append(envelopes[k])
27+
else:
28+
i = bisect.bisect_left(seq, envelopes[k][1], key=lambda x: x[1])
29+
seq[i] = envelopes[k]
30+
return len(seq)
31+
32+
def maxEnvelopesDP(self, envelopes: List[List[int]]) -> int:
33+
"""
34+
You are given a 2D array of integers envelopes where envelopes[i] = [wi, hi]
35+
represents the width and the height of an envelope.
36+
37+
One envelope can fit into another if and only if both the width and height of
38+
one envelope are greater than the other envelope's width and height.
39+
40+
Return the maximum number of envelopes you can Russian doll (i.e., put one
41+
inside the other).
42+
43+
Note: You cannot rotate an envelope.
44+
"""
45+
# DP (LIS) Solution: O(n^2)
46+
# Invalid: TLE
47+
envelopes = sorted(envelopes)
48+
dp = [1 for _ in range(len(envelopes))]
49+
for i in range(len(envelopes) - 2, -1, -1):
50+
for j in range(i + 1, len(envelopes)):
51+
if (
52+
envelopes[i][0] < envelopes[j][0]
53+
and envelopes[i][1] < envelopes[j][1]
54+
):
55+
dp[i] = max(dp[i], 1 + dp[j])
56+
return max(dp)
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
"""Base class for all LeetCode Problems."""
6+
7+
def findLongestChain(self, pairs: List[List[int]]) -> int:
8+
"""
9+
You are given an array of n pairs pairs where pairs[i] = [lefti, righti] and
10+
lefti < righti.
11+
12+
A pair p2 = [c, d] follows a pair p1 = [a, b] if b < c. A chain of pairs can be
13+
formed in this fashion.
14+
15+
Return the length longest chain which can be formed.
16+
17+
You do not need to use up all the given intervals. You can select pairs in any
18+
order.
19+
"""
20+
pairs = sorted(pairs)
21+
dp = [1 for _ in range(len(pairs))]
22+
for i in range(len(pairs) - 2, -1, -1):
23+
for j in range(i + 1, len(pairs)):
24+
if pairs[i][1] < pairs[j][0]:
25+
dp[i] = max(dp[i], 1 + dp[j])
26+
return max(dp)
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._1027_longest_arithmetic_subsequence import Solution
6+
7+
8+
@pytest.mark.parametrize(
9+
argnames=["nums", "expected"],
10+
argvalues=[
11+
([3, 6, 9, 12], 4),
12+
([9, 4, 7, 2, 10], 3),
13+
([20, 1, 15, 3, 10, 5, 8], 4),
14+
],
15+
)
16+
def test_func(nums: List[int], expected: int):
17+
"""Tests the solution of a LeetCode problem."""
18+
longest_arithmetic_sequence = Solution().longestArithSeqLength(nums)
19+
assert longest_arithmetic_sequence == expected
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# flake8: noqa
2+
from typing import List
3+
4+
import pytest
5+
6+
from awesome_python_leetcode._1218_longest_arithmetic_subsequence_of_given_difference import (
7+
Solution,
8+
)
9+
10+
11+
@pytest.mark.parametrize(
12+
argnames=["arr", "difference", "expected"],
13+
argvalues=[
14+
([1, 2, 3, 4], 1, 4),
15+
([1, 3, 5, 7], 1, 1),
16+
([1, 5, 7, 8, 5, 3, 4, 2, 1], -2, 4),
17+
],
18+
)
19+
def test_func(arr: List[int], difference: int, expected: int):
20+
"""Tests the solution of a LeetCode problem."""
21+
longest_subsequence = Solution().longestSubsequence(arr, difference)
22+
assert longest_subsequence == expected
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# flake8: noqa
2+
from typing import List
3+
4+
import pytest
5+
6+
from awesome_python_leetcode._1964_find_the_longest_valid_obstacle_course_at_each_position import (
7+
Solution,
8+
)
9+
10+
11+
@pytest.mark.parametrize(
12+
argnames=["obstacles", "expected"],
13+
argvalues=[
14+
([1, 2, 3, 2], [1, 2, 3, 3]),
15+
([2, 2, 1], [1, 2, 1]),
16+
([3, 1, 5, 6, 4, 2], [1, 1, 2, 3, 2, 2]),
17+
],
18+
)
19+
def test_func(obstacles: List[int], expected: List[int]):
20+
"""Tests the solution of a LeetCode problem."""
21+
longest_obstacles = Solution().longestObstacleCourseAtEachPosition(obstacles)
22+
assert longest_obstacles == expected
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
from typing import List
2+
3+
import pytest
4+
5+
from awesome_python_leetcode._354_russian_doll_envelopes import Solution
6+
7+
8+
@pytest.mark.parametrize(
9+
argnames=["envelopes", "expected"],
10+
argvalues=[
11+
([[5, 4], [6, 4], [6, 7], [2, 3]], 3),
12+
([[1, 1], [1, 1], [1, 1]], 1),
13+
([[4, 5], [4, 6], [6, 7], [2, 3], [1, 1]], 4),
14+
],
15+
)
16+
def test_func_bs(envelopes: List[List[int]], expected: int):
17+
"""Tests the solution of a LeetCode problem."""
18+
max_envelopes = Solution().maxEnvelopesBS(envelopes)
19+
assert max_envelopes == expected
20+
21+
22+
@pytest.mark.parametrize(
23+
argnames=["envelopes", "expected"],
24+
argvalues=[
25+
([[5, 4], [6, 4], [6, 7], [2, 3]], 3),
26+
([[1, 1], [1, 1], [1, 1]], 1),
27+
([[4, 5], [4, 6], [6, 7], [2, 3], [1, 1]], 4),
28+
],
29+
)
30+
def test_func_dp(envelopes: List[List[int]], expected: int):
31+
"""Tests the solution of a LeetCode problem."""
32+
max_envelopes = Solution().maxEnvelopesDP(envelopes)
33+
assert max_envelopes == expected

0 commit comments

Comments
 (0)