Tuesday, 7 September 2021
BinarySearch - Increasing Subsequences of Size K
[https://binarysearch.com/problems/Increasing-Subsequences-of-Size-K](https://binarysearch.com/problems/Increasing-Subsequences-of-Size-K)
## Problem
Given a list of integers nums and an integer k, return the number of subsequences of size k that are strictly increasing.
Mod the result by 10 ** 9 + 7.
Constraints
0 ≤ n ≤ 1,000 where n is the length of nums.
1 ≤ k ≤ 10
## Solution
Use Dynamic Programming.
Define dp[i][j] to store the count of increasing subsequences of size i ending with element nums[j].
$dp[i][j] = 1$, where $i = 1$ and $1 <= j <= n $
$dp[i][j] = dp[i][j] + dp[i - 1][j]$, where $1 < i <= k$, $i <= j <= n$ and $nums[m] < nums[j]$ for $(i - 1) <= m < j$.
                                                                                          
Time Complexity: $O(k * n ^ 2)$
                                                                                                                       
Space Complexity: $O(k * n)$
```
int solve(vector& nums, int k) {
    int n = (int)nums.size(), dp[k][n], ans = 0, mod = 1e9 + 7;
    memset(dp, 0, sizeof(dp));
    for (int i = 0; i < n; i++) dp[0][i] = 1;
    for (int l = 1; l < k; l++) {
        for (int i = l; i < n; i++) {
            dp[l][i] = 0;
            for (int j = l - 1; j < i; j++) {
                if (nums[j] < nums[i]) {
                    dp[l][i] = (dp[l][i] + dp[l - 1][j]) % mod;
                }
            }
        }
    }
    for (int i = k - 1; i < n; i++) {
        ans = (ans + dp[k - 1][i]) % mod;
    }
    return ans;
}
```
 
Subscribe to:
Post Comments (Atom)
A Fun Problem - Math
# Problem Statement JATC's math teacher always gives the class some interesting math problems so that they don't get bored. Today t...
- 
SHA stands for Secure Hashing Algorithm and 2 is just a version number. SHA-2 revises the construction and the big-length of the signature f...
 - 
## SQRT Decomposition Square Root Decomposition is an technique optimizating common operations in time complexity O(sqrt(N)). The idea of t...
 
No comments:
Post a Comment