# Code language: Python classSolution: defmaxScore(self, s: str) -> int: left0, right1 = int(s[0] == '0'), s.count('1') - int(s[0] == '1') ans = left0 + right1 for i inrange(1, len(s) - 1): if s[i] == '0': left0 += 1 else: right1 -= 1 ans = max(ans, left0 + right1) return ans
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// Code language: Java classSolution { publicintmaxScore(String s) { intleft=0, right = 0, ans, n = s.length() - 1; if (s.charAt(0) == '0') ++left; for (inti=1; i <= n; ++i) if (s.charAt(i) == '1') ++right; ans = left + right; for (inti=1; i < n; ++i) { if (s.charAt(i) == '0') ++left; else --right; ans = Math.max(ans, left + right); } return ans; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// Code language: C++ classSolution { public: intmaxScore(string s){ int left = 0, right = 0, ans, n = s.size() - 1; if (s[0] == '0') ++left; for (int i = 1; i <= n; ++i) if (s[i] == '1') ++right; ans = left + right; for (int i = 1; i < n; ++i) { if (s[i] == '0') ++left; else --right; ans = max(ans, left + right); } return ans; } };