File tree 2 files changed +51
-0
lines changed
2 files changed +51
-0
lines changed Original file line number Diff line number Diff line change 713
713
900|[ RLE Iterator] ( ./0900-rle-iterator.js ) |Medium|
714
714
901|[ Online Stock Span] ( ./0901-online-stock-span.js ) |Medium|
715
715
902|[ Numbers At Most N Given Digit Set] ( ./0902-numbers-at-most-n-given-digit-set.js ) |Hard|
716
+ 903|[ Valid Permutations for DI Sequence] ( ./0903-valid-permutations-for-di-sequence.js ) |Hard|
716
717
905|[ Sort Array By Parity] ( ./0905-sort-array-by-parity.js ) |Easy|
717
718
909|[ Snakes and Ladders] ( ./0909-snakes-and-ladders.js ) |Medium|
718
719
912|[ Sort an Array] ( ./0912-sort-an-array.js ) |Medium|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 903. Valid Permutations for DI Sequence
3
+ * https://leetcode.com/problems/valid-permutations-for-di-sequence/
4
+ * Difficulty: Hard
5
+ *
6
+ * You are given a string s of length n where s[i] is either:
7
+ * - 'D' means decreasing, or
8
+ * - 'I' means increasing.
9
+ *
10
+ * A permutation perm of n + 1 integers of all the integers in the range [0, n] is called a
11
+ * valid permutation if for all valid i:
12
+ * - If s[i] == 'D', then perm[i] > perm[i + 1], and
13
+ * - If s[i] == 'I', then perm[i] < perm[i + 1].
14
+ *
15
+ * Return the number of valid permutations perm. Since the answer may be large, return it
16
+ * modulo 109 + 7.
17
+ */
18
+
19
+ /**
20
+ * @param {string } s
21
+ * @return {number }
22
+ */
23
+ var numPermsDISequence = function ( s ) {
24
+ const MOD = 1e9 + 7 ;
25
+ const n = s . length ;
26
+ const dp = Array . from ( { length : n + 1 } , ( ) => new Array ( n + 1 ) . fill ( 0 ) ) ;
27
+
28
+ dp [ 0 ] [ 0 ] = 1 ;
29
+
30
+ for ( let len = 1 ; len <= n ; len ++ ) {
31
+ for ( let curr = 0 ; curr <= len ; curr ++ ) {
32
+ if ( s [ len - 1 ] === 'D' ) {
33
+ for ( let prev = curr ; prev < len ; prev ++ ) {
34
+ dp [ len ] [ curr ] = ( dp [ len ] [ curr ] + dp [ len - 1 ] [ prev ] ) % MOD ;
35
+ }
36
+ } else {
37
+ for ( let prev = 0 ; prev < curr ; prev ++ ) {
38
+ dp [ len ] [ curr ] = ( dp [ len ] [ curr ] + dp [ len - 1 ] [ prev ] ) % MOD ;
39
+ }
40
+ }
41
+ }
42
+ }
43
+
44
+ let result = 0 ;
45
+ for ( let num = 0 ; num <= n ; num ++ ) {
46
+ result = ( result + dp [ n ] [ num ] ) % MOD ;
47
+ }
48
+
49
+ return result ;
50
+ } ;
You can’t perform that action at this time.
0 commit comments