File tree 1 file changed +14
-25
lines changed
1 file changed +14
-25
lines changed Original file line number Diff line number Diff line change 2
2
* @param {number[] } nums
3
3
* @return {number }
4
4
*/
5
- var sumOfGoodSubsequences = function ( nums ) {
6
- const mod = 1000000007n ;
7
- const MAX = 100005 ;
8
- const sum = new Array ( MAX ) . fill ( 0n ) ;
9
- const cnt = new Array ( MAX ) . fill ( 0n ) ;
10
-
11
- for ( let i = nums . length - 1 ; i >= 0 ; i -- ) {
12
- const v = nums [ i ] ;
13
- cnt [ v ] ++ ;
14
-
15
- const tmp = 1n + cnt [ v + 1 ] + ( cnt [ v - 1 ] || 0n ) ;
16
- cnt [ v ] += cnt [ v + 1 ] ;
17
- cnt [ v ] += cnt [ v - 1 ] || 0n ;
18
-
19
- sum [ v ] += BigInt ( v ) * tmp ;
20
-
21
- sum [ v ] += sum [ v + 1 ] ;
22
- sum [ v ] += sum [ v - 1 ] || 0n ;
23
-
24
- cnt [ v ] %= mod ;
25
- sum [ v ] %= mod ;
26
- }
27
-
28
- return Number ( sum . reduce ( ( a , b ) => ( a + b ) % mod , 0n ) ) ;
29
- }
5
+ const sumOfGoodSubsequences = function ( nums ) {
6
+ const limit = 1e5 + 10 ;
7
+ const mod = 1e9 + 7 ;
8
+ const count = Array ( limit ) . fill ( 0 ) ;
9
+ const total = Array ( limit ) . fill ( 0 ) ;
10
+ let res = 0 ;
11
+ for ( const e of nums ) {
12
+ count [ e + 1 ] = ( count [ e ] + count [ e + 1 ] + count [ e + 2 ] + 1 ) % mod
13
+ const cur = total [ e ] + total [ e + 2 ] + e * ( count [ e ] + count [ e + 2 ] + 1 )
14
+ total [ e + 1 ] = ( total [ e + 1 ] + cur ) % mod
15
+ res = ( res + cur ) % mod
16
+ }
17
+ return res
18
+ } ;
You can’t perform that action at this time.
0 commit comments