Skip to content

Commit bee9364

Browse files
authored
Create number-of-ways-to-rearrange-sticks-with-k-sticks-visible.cpp
1 parent e5c8cd7 commit bee9364

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// Time: O(n * k)
2+
// Space: O(k)
3+
4+
class Solution {
5+
public:
6+
int rearrangeSticks(int n, int k) {
7+
static const int MOD = 1e9 + 7;
8+
vector<vector<int>> dp(2, vector<int>(k + 1));
9+
dp[1][1] = 1;
10+
for (int i = 2; i <= n; ++i) {
11+
for (int j = 1; j <= min(i, k); ++j) {
12+
// choose the tallest as the last one which would be visible: dp[i-1][j-1]
13+
// choose the non-tallest as the last one which would be hidden: (i-1) * dp[i-1][j]
14+
dp[i % 2][j] = (dp[(i - 1) % 2][j - 1] + int64_t(i - 1) * dp[(i - 1) % 2][j]) % MOD;
15+
}
16+
}
17+
return dp[n % 2][k];
18+
}
19+
};

0 commit comments

Comments
 (0)