Tensorum
YouTubeশেখা শুরু করুন
LeetCode 673 · LIS

Number of Longest Increasing Subsequence

LeetCode 673 · মাঝারি · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু

Longer ⇒ copy the count; equal ⇒ add the count.

মাঝারিArrayDynamic ProgrammingBinary Indexed TreeSegment TreeLongest Increasing Subsequence
LeetCode-এ খুলুন ↗

আমি 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. 1

    dp[i] = LIS length ending at i; count[i] = number of such sequences.

  2. 2

    For every j < i with nums[j] < nums[i]: compare dp[j] + 1 against dp[i].

  3. 3

    Longer: set dp[i] and copy count[j]. Equal: add count[j].

  4. 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 result
স্টেপ-থ্রু লোড হচ্ছে…

Number 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.