C++ 算法:最大化金牌连续长度
以下是用C++解决该问题的代码:
#include <iostream>
#include <vector>
using namespace std;
int maxGoldMedalLength(int n, string medals) {
vector<int> goldCount(n, 0); // 记录每个位置之前的金牌数量
int count = 0;
for (int i = 0; i < n; i++) {
if (medals[i] == 'G') {
count++;
}
goldCount[i] = count;
}
int maxLen = count; // 初始最长金牌连续长度
// 从左到右遍历每个位置,尝试将该位置的奖牌交换到最后一个金牌位置
for (int i = 0; i < n; i++) {
int goldLen = goldCount[i]; // 金牌连续长度
int silverLen = i + 1 - goldLen; // 银牌连续长度
if (i < n - 1 && medals[i] == 'S' && medals[i + 1] == 'G') {
// 如果当前位置为银牌且下一个位置为金牌,则交换两个位置的奖牌
goldLen++;
silverLen--;
}
maxLen = max(maxLen, goldLen);
}
return maxLen;
}
int main() {
int n;
cin >> n;
string medals;
cin >> medals;
int maxGoldLen = maxGoldMedalLength(n, medals);
cout << maxGoldLen << endl;
return 0;
}
输入示例:
10
GGGSGGGSGG
输出示例:
7
原文地址: https://www.cveoy.top/t/topic/quNE 著作权归作者所有。请勿转载和采集!