C++ 算法:最大化金牌连续段长度
以下是解决该问题的 C++ 代码:
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
string medals;
cin >> medals;
int goldCount = 0;
vector<int> goldCounts(n, 0); // 记录每个位置之前的金牌数量
for (int i = 0; i < n; i++) {
if (medals[i] == 'G') {
goldCount++;
}
goldCounts[i] = goldCount;
}
int maxGoldLength = 0;
for (int i = 0; i < n; i++) {
int goldLength = goldCounts[i];
if (medals[i] == 'S') {
// 尝试将当前银牌与之前的金牌交换位置
if (i > 0 && medals[i-1] == 'G') {
goldLength++;
}
// 尝试将当前银牌与之后的金牌交换位置
if (i < n-1 && medals[i+1] == 'G') {
goldLength++;
}
}
maxGoldLength = max(maxGoldLength, goldLength);
}
cout << maxGoldLength << endl;
return 0;
}
该代码的思路是首先统计每个位置之前的金牌数量,然后遍历每个位置,计算在当前位置将银牌与之前或之后的金牌交换位置后,能够得到的最长金牌连续段长度。最终输出最长金牌连续段长度。
原文地址: https://www.cveoy.top/t/topic/quNJ 著作权归作者所有。请勿转载和采集!