-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0903-valid-permutations-for-di-sequence.js
More file actions
56 lines (50 loc) · 1.71 KB
/
0903-valid-permutations-for-di-sequence.js
File metadata and controls
56 lines (50 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
* Valid Permutations For Di Sequence
* Time Complexity: O(n^2)
* Space Complexity: O(n)
*/
var numPermsDISequence = function (s) {
const sLength = s.length;
const moduloValue = 1e9 + 7;
let previousDpRow = new Array(1).fill(1);
let previousPrefixSums = new Array(1).fill(1);
for (
let currentSegmentLength = 1;
currentSegmentLength <= sLength;
currentSegmentLength++
) {
let currentDpRow = new Array(currentSegmentLength + 1).fill(0);
let currentPrefixSums = new Array(currentSegmentLength + 1).fill(0);
let relationCharacter = s[currentSegmentLength - 1];
for (
let currentPermutationRank = 0;
currentPermutationRank <= currentSegmentLength;
currentPermutationRank++
) {
if (relationCharacter === "D") {
let decreasingSum =
(previousPrefixSums[currentSegmentLength - 1] -
(currentPermutationRank > 0
? previousPrefixSums[currentPermutationRank - 1]
: 0) +
moduloValue) %
moduloValue;
currentDpRow[currentPermutationRank] = decreasingSum;
} else {
let increasingSum =
(currentPermutationRank > 0
? previousPrefixSums[currentPermutationRank - 1]
: 0) % moduloValue;
currentDpRow[currentPermutationRank] = increasingSum;
}
}
for (let sumIndex = 0; sumIndex <= currentSegmentLength; sumIndex++) {
let priorPrefixValue = sumIndex > 0 ? currentPrefixSums[sumIndex - 1] : 0;
currentPrefixSums[sumIndex] =
(priorPrefixValue + currentDpRow[sumIndex]) % moduloValue;
}
previousDpRow = currentDpRow;
previousPrefixSums = currentPrefixSums;
}
return previousPrefixSums[sLength];
};