LCP 19. 秋叶收藏集
小扣出去秋游,途中收集了一些红叶和黄叶,他利用这些叶子初步整理了一份秋叶收藏集 leaves, 字符串 leaves 仅包含小写字符 r 和 y, 其中字符 r 表示一片红叶,字符 y 表示一片黄叶。
出于美观整齐的考虑,小扣想要将收藏集中树叶的排列调整成「红、黄、红」三部分。每部分树叶数量可以不相等,但均需大于等于 1。每次调整操作,小扣可以将一片红叶替换成黄叶或者将一片黄叶替换成红叶。请问小扣最少需要多少次调整操作才能将秋叶收藏集调整完毕。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/UlBDOe
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
/**
* preYellow[0, x] + preRed[x + 1, y] + preYellow[y + 1, n - 1]
* preYellow[x] + (preRed[y] - preRed[x]) + (preYellow[n-1] - preYellow[y])
* (preYellow[x] - preRed[x]) + (preRed[y] - preYellow[y]) + preYellow[n-1]
* dp + (preRed[y] - preYellow[y]) + preYellow[n-1]
*/
public int minimumOperations(String leaves) {
int ans = leaves.length();
int dp = leaves.charAt(0) == 'y' ? 1 : -1;
int preYellow = leaves.charAt(0) == 'y' ? 1 : 0, preRed = leaves.charAt(0) == 'r' ? 1 : 0;
for (int i = 1; i < leaves.length(); ++i) {
preYellow += leaves.charAt(i) == 'y' ? 1 : 0;
preRed += leaves.charAt(i) == 'r' ? 1 : 0;
if (i != leaves.length() - 1) {
ans = Math.min(ans, dp + (preRed - preYellow));
}
dp = Math.min(dp, preYellow - preRed);
}
return ans + preYellow;
}
}
心之所向,素履以往 生如逆旅,一苇以航

浙公网安备 33010602011771号