File tree Expand file tree Collapse file tree
src/test/java/LeetCode/Maximize_the_Number_of_Partitions_After_Operations Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ public class LC_maxnopartafterop {
2+
3+ public int maxPartitionsAfterOperations (String s , int k ) {
4+ int n = s .length ();
5+ int [][] left = new int [n ][3 ];
6+ int [][] right = new int [n ][3 ];
7+
8+ int num = 0 ;
9+ int mask = 0 ;
10+ int count = 0 ;
11+ for (int i = 0 ; i < n - 1 ; i ++) {
12+ int binary = 1 << (s .charAt (i ) - 'a' );
13+ if ((mask & binary ) == 0 ) {
14+ count ++;
15+ if (count <= k ) {
16+ mask |= binary ;
17+ } else {
18+ num ++;
19+ mask = binary ;
20+ count = 1 ;
21+ }
22+ }
23+ left [i + 1 ][0 ] = num ;
24+ left [i + 1 ][1 ] = mask ;
25+ left [i + 1 ][2 ] = count ;
26+ }
27+
28+ num = 0 ;
29+ mask = 0 ;
30+ count = 0 ;
31+ for (int i = n - 1 ; i > 0 ; i --) {
32+ int binary = 1 << (s .charAt (i ) - 'a' );
33+ if ((mask & binary ) == 0 ) {
34+ count ++;
35+ if (count <= k ) {
36+ mask |= binary ;
37+ } else {
38+ num ++;
39+ mask = binary ;
40+ count = 1 ;
41+ }
42+ }
43+ right [i - 1 ][0 ] = num ;
44+ right [i - 1 ][1 ] = mask ;
45+ right [i - 1 ][2 ] = count ;
46+ }
47+
48+ int maxVal = 0 ;
49+ for (int i = 0 ; i < n ; i ++) {
50+ int seg = left [i ][0 ] + right [i ][0 ] + 2 ;
51+ int totMask = left [i ][1 ] | right [i ][1 ];
52+ int totCount = Integer .bitCount (totMask );
53+ if (left [i ][2 ] == k && right [i ][2 ] == k && totCount < 26 ) {
54+ seg ++;
55+ } else if (Math .min (totCount + 1 , 26 ) <= k ) {
56+ seg --;
57+ }
58+ maxVal = Math .max (maxVal , seg );
59+ }
60+ return maxVal ;
61+ }
62+ }
You can’t perform that action at this time.
0 commit comments