Skip to content

Commit b3bc1fa

Browse files
committed
Implement solution for 1422 maximum score after splitting a string in C, C++, Python, and Rust
1 parent d4f5973 commit b3bc1fa

File tree

4 files changed

+93
-0
lines changed

4 files changed

+93
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
#include <string.h>
2+
3+
4+
int maxScore(char* s) {
5+
int left_zeros = 0, right_ones = 0, max_score = 0;
6+
// count total number of ones
7+
for (int i = 0; s[i]!='\0'; i++) {
8+
if (s[i] == '1') right_ones++;
9+
10+
}
11+
12+
// traverse the string
13+
for (int i = 0; s[i+1] != '\0'; i++) {
14+
if (s[i] == '0'){
15+
left_zeros++;
16+
17+
} else {
18+
right_ones--;
19+
}
20+
21+
// calculate the score
22+
int score = left_zeros + right_ones;
23+
if (score > max_score) max_score = score;
24+
}
25+
26+
return max_score;
27+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution {
2+
public:
3+
int maxScore(string s) {
4+
int left_zeros = 0, right_ones = count(s.begin(), s.end(), '1');
5+
int max_score = 0;
6+
7+
8+
// Traverse the entire string
9+
for (int i = 0; i < s.size()-1; ++i) {
10+
if (s[i] == '0') {
11+
left_zeros++;
12+
13+
} else {
14+
right_ones--;
15+
}
16+
17+
// calculate the score
18+
max_score = max(max_score, left_zeros+right_ones);
19+
}
20+
21+
return max_score;
22+
}
23+
};
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution:
2+
def maxScore(self, s:str) -> int:
3+
# initialize the counts
4+
left_zeros = 0
5+
right_ones = s.count('1') # how many ones are in the string
6+
max_score = 0
7+
8+
9+
# now traverse the string
10+
for i in range(len(s)-1): # since split point must leave a non-empty substring
11+
if s[i] == '0':
12+
left_zeros += 1
13+
else:
14+
right_ones -= 1
15+
16+
# now calculate the score
17+
max_score = max(max_score, left_zeros + right_ones)
18+
19+
return max_score
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
impl Solution {
2+
pub fn max_score(s: String) -> i32 {
3+
let chars: Vec<char> = s.chars().collect();
4+
let mut left_zeros = 0;
5+
let mut right_ones = chars.iter().filter(|&&c| c == '1').count() as i32;
6+
let mut max_score = 0;
7+
8+
9+
for i in 0..chars.len()-1 {
10+
if chars[i] == '0' {
11+
left_zeros += 1;
12+
13+
} else {
14+
right_ones -= 1;
15+
16+
}
17+
18+
max_score = max_score.max(left_zeros + right_ones);
19+
}
20+
21+
max_score
22+
23+
}
24+
}

0 commit comments

Comments
 (0)