File tree 1 file changed +24
-17
lines changed
scripts/algorithms/M/Maximum Score After Splitting a String
1 file changed +24
-17
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 45 ms (Top 96.83%) | Memory: 48.50 MB (Top 8.24%)
2
+
3
+ /**
1
4
* @param {string } s
2
5
* @return {number }
3
6
*/
4
7
var maxScore = function ( s ) {
5
- const leftScores = [ ]
6
- const rightScores = [ ]
7
- let score = 0
8
- for ( let i = 0 ; i < s . length - 1 ; i ++ ) {
9
- if ( s [ i ] === '0' )
10
- score ++
11
- leftScores . push ( score )
12
- }
13
- score = 0
14
- for ( let i = s . length - 1 ; i > 0 ; i -- ) {
15
- if ( s [ i ] === '1' )
16
- score ++
17
- rightScores . unshift ( score )
18
- }
19
-
20
- const scores = leftScores . map ( ( val , idx ) => val + rightScores [ idx ] )
21
- return Math . max ( ...scores )
8
+ const length = s . length ;
9
+ let ones = 0 ;
10
+ let tmpScore = s [ 0 ] === '0' ? 1 : 0 ;
11
+ let score = tmpScore ;
12
+
13
+ for ( let i = 1 ; i < length - 1 ; i ++ ) {
14
+ if ( s [ i ] === '0' ) {
15
+ tmpScore += 1 ;
16
+ } else {
17
+ ones += 1 ;
18
+ tmpScore -= 1 ;
19
+ }
20
+
21
+ if ( tmpScore > score ) {
22
+ score = tmpScore ;
23
+ }
24
+ }
25
+
26
+ ones += s [ length - 1 ] === '1' ? 1 : 0 ;
27
+
28
+ return ones + score ;
22
29
} ;
You can’t perform that action at this time.
0 commit comments