因此我们只需要在枚举 y 的同时计算 g 值即可,并且 pre}_Y(n-1) 这一常数项可以留在最后再累加,它就等于:
\textit{pre}_Y(n-1) = g(n-1) + n}{2}
代码
[sol2-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution { public: intminimumOperations(string leaves){ int n = leaves.size(); int g = (leaves[0] == 'y' ? 1 : -1); int gmin = g; int ans = INT_MAX; for (int i = 1; i < n; ++i) { int isYellow = (leaves[i] == 'y'); g += 2 * isYellow - 1; if (i != n - 1) { ans = min(ans, gmin - g); } gmin = min(gmin, g); } return ans + (g + n) / 2; } };
[sol2-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution { publicintminimumOperations(String leaves) { intn= leaves.length(); intg= leaves.charAt(0) == 'y' ? 1 : -1; intgmin= g; intans= Integer.MAX_VALUE; for (inti=1; i < n; ++i) { intisYellow= leaves.charAt(i) == 'y' ? 1 : 0; g += 2 * isYellow - 1; if (i != n - 1) { ans = Math.min(ans, gmin - g); } gmin = Math.min(gmin, g); } return ans + (g + n) / 2; } }
[sol2-Python3]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution: defminimumOperations(self, leaves: str) -> int: n = len(leaves) g = (1if leaves[0] == "y"else -1) gmin = g ans = float("inf")
for i inrange(1, n): isYellow = int(leaves[i] == "y") g += 2 * isYellow - 1 if i != n - 1: ans = min(ans, gmin - g) gmin = min(gmin, g) return ans + (g + n) // 2
funcminimumOperations(leaves string)int { n := len(leaves) g := -1 if leaves[0] == 'y' { g = 1 } gmin := g ans := inf for i := 1; i < n; i++ { isYellow := boolToInt(leaves[i] == 'y') g += 2*isYellow - 1 if i != n-1 { ans = min(ans, gmin-g) } gmin = min(gmin, g) } return ans + (g+n)/2 }
funcboolToInt(b bool)int { if b { return1 } return0 }
funcmin(a, b int)int { if a < b { return a } return b }
[sol2-C]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
intminimumOperations(char* leaves) { int n = strlen(leaves); int g = (leaves[0] == 'y' ? 1 : -1); int gmin = g; int ans = INT_MAX; for (int i = 1; i < n; ++i) { int isYellow = (leaves[i] == 'y'); g += 2 * isYellow - 1; if (i != n - 1) { ans = fmin(ans, gmin - g); } gmin = fmin(gmin, g); } return ans + (g + n) / 2; }