Leetcode 3228. Maximum Number of Operations to Move Ones to the End

1. 解题思路

这一题不难分析得到,要获得最多的操作次数,只需要从左往右依次执行即可,此时,每一次遇到一个10结构,能够执行的操作次数就是其左侧所有的1的个数。

我们将其翻译为代码语言即可。

2. 代码实现

给出python代码实现如下:

class Solution:
    def maxOperations(self, s: str) -> int:
        pre = 0
        ans = 0
        for i, ch in enumerate(s):
            if ch == "1":
                pre += 1
            elif i > 0 and s[i-1] == "1":
                ans += pre
        return ans

提交代码评测得到:耗时91ms,占用内存17.3MB。