Skip to content

Commit 7ea26f9

Browse files
authored
Create number-of-ways-to-rearrange-sticks-with-k-sticks-visible.py
1 parent bee9364 commit 7ea26f9

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(object):
5+
def rearrangeSticks(self, n, k):
6+
"""
7+
:type n: int
8+
:type k: int
9+
:rtype: int
10+
"""
11+
MOD = 10**9+7
12+
dp = [[0 for _ in xrange(k+1)] for _ in xrange(2)]
13+
dp[1][1] = 1
14+
for i in xrange(2, n+1):
15+
for j in xrange(1, min(i, k)+1):
16+
# choose the tallest as the last one which would be visible: dp[i-1][j-1]
17+
# choose the non-tallest as the last one which would be hidden: (i-1)*dp[i-1][j]
18+
dp[i%2][j] = (dp[(i-1)%2][j-1]+(i-1)*dp[(i-1)%2][j]) % MOD
19+
return dp[n%2][k]

0 commit comments

Comments
 (0)