Skip to content

Commit ac41b3d

Browse files
committed
Sync LeetCode submission Runtime - 0 ms (100.00%), Memory - 17.8 MB (16.51%)
1 parent dc5bd69 commit ac41b3d

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
<p>Given a&nbsp;string <code>s</code>&nbsp;of zeros and ones, <em>return the maximum score after splitting the string into two <strong>non-empty</strong> substrings</em> (i.e. <strong>left</strong> substring and <strong>right</strong> substring).</p>
2+
3+
<p>The score after splitting a string is the number of <strong>zeros</strong> in the <strong>left</strong> substring plus the number of <strong>ones</strong> in the <strong>right</strong> substring.</p>
4+
5+
<p>&nbsp;</p>
6+
<p><strong class="example">Example 1:</strong></p>
7+
8+
<pre>
9+
<strong>Input:</strong> s = &quot;011101&quot;
10+
<strong>Output:</strong> 5
11+
<strong>Explanation:</strong>
12+
All possible ways of splitting s into two non-empty substrings are:
13+
left = &quot;0&quot; and right = &quot;11101&quot;, score = 1 + 4 = 5
14+
left = &quot;01&quot; and right = &quot;1101&quot;, score = 1 + 3 = 4
15+
left = &quot;011&quot; and right = &quot;101&quot;, score = 1 + 2 = 3
16+
left = &quot;0111&quot; and right = &quot;01&quot;, score = 1 + 1 = 2
17+
left = &quot;01110&quot; and right = &quot;1&quot;, score = 2 + 1 = 3
18+
</pre>
19+
20+
<p><strong class="example">Example 2:</strong></p>
21+
22+
<pre>
23+
<strong>Input:</strong> s = &quot;00111&quot;
24+
<strong>Output:</strong> 5
25+
<strong>Explanation:</strong> When left = &quot;00&quot; and right = &quot;111&quot;, we get the maximum score = 2 + 3 = 5
26+
</pre>
27+
28+
<p><strong class="example">Example 3:</strong></p>
29+
30+
<pre>
31+
<strong>Input:</strong> s = &quot;1111&quot;
32+
<strong>Output:</strong> 3
33+
</pre>
34+
35+
<p>&nbsp;</p>
36+
<p><strong>Constraints:</strong></p>
37+
38+
<ul>
39+
<li><code>2 &lt;= s.length &lt;= 500</code></li>
40+
<li>The string <code>s</code> consists of characters <code>&#39;0&#39;</code> and <code>&#39;1&#39;</code> only.</li>
41+
</ul>
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Approach 2: Count Left Zeros and Right Ones
2+
3+
# Time: O(n)
4+
# Space: O(1)
5+
6+
class Solution:
7+
def maxScore(self, s: str) -> int:
8+
ones = s.count('1')
9+
zeros = 0
10+
ans = 0
11+
12+
for i in range(len(s) - 1):
13+
if s[i] == '1':
14+
ones -= 1
15+
else:
16+
zeros += 1
17+
18+
ans = max(ans, ones + zeros)
19+
20+
return ans
21+

0 commit comments

Comments
 (0)