Number of Longest Increasing Subsequence
LeetCode 673 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
Longer ⇒ copy the count; equal ⇒ add the count.
मैंने Number of Longest Increasing Subsequence (LeetCode 673) ऐसे हल किया — LIS पैटर्न का एक मध्यम प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।
नीचे का विवरण अंग्रेज़ी में है।
Intuition
Alongside the LIS length ending at each index, also count how many sequences reach that length. When an earlier element gives a strictly longer run, its count replaces ours; when it ties, its count adds to ours.
Approach
- 1
dp[i] = LIS length ending at i; count[i] = number of such sequences.
- 2
For every j < i with nums[j] < nums[i]: compare dp[j] + 1 against dp[i].
- 3
Longer: set dp[i] and copy count[j]. Equal: add count[j].
- 4
Sum count[i] over all i whose dp[i] equals the overall max.
मैंने कैसे हल किया
LIS with countsPythonO(n²) time · O(n) space
class Solution:
#1,3,5,4,7
def findNumberOfLIS(self, nums: List[int]) -> int:
dp=[1]*len(nums)
count=[1]*len(nums)
for i in range(len(nums)):
for j in range(i):
if nums[i]>nums[j]:
if dp[j]+1>dp[i]:
dp[i]=dp[j]+1
count[i]=count[j] #copy
elif dp[j]+1==dp[i]:
count[i]+=count[j] #add
lis=max(dp)
result=0
for i in range(len(nums)):
if dp[i]==lis:
result+=count[i]
return resultNumber of Longest Increasing Subsequence — अक्सर पूछे जाने वाले प्रश्न
Number of Longest Increasing Subsequence के पीछे intuition क्या है?
Alongside the LIS length ending at each index, also count how many sequences reach that length. When an earlier element gives a strictly longer run, its count replaces ours; when it ties, its count adds to ours.
Number of Longest Increasing Subsequence (LeetCode 673) कैसे हल करें?
1. dp[i] = LIS length ending at i; count[i] = number of such sequences. 2. For every j < i with nums[j] < nums[i]: compare dp[j] + 1 against dp[i]. 3. Longer: set dp[i] and copy count[j]. Equal: add count[j]. 4. Sum count[i] over all i whose dp[i] equals the overall max.
Number of Longest Increasing Subsequence की time और space complexity क्या है?
Time: O(n²)। Space: O(n)। (Accepted approach: LIS with counts।)
Number of Longest Increasing Subsequence में आम गलतियाँ क्या हैं?
Sum counts over every index that reaches the max length, not just the last one.