Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

31. 字符串的最大价值 c++版本答案 #84

Open
Maxxiaoshuai opened this issue Aug 30, 2023 · 1 comment
Open

31. 字符串的最大价值 c++版本答案 #84

Maxxiaoshuai opened this issue Aug 30, 2023 · 1 comment

Comments

@Maxxiaoshuai
Copy link

#include
#include
#include
#include
#include <math.h>
#include
using namespace std;

// 通过计算不同部分连续字符对最终价值的贡献来得到最大的价值。
int findMaxVal(string &s, char c) {
// 1. 找到第一个字符 c 出现的位置 start 和最后一个字符 c 出现的位置 end。
int start = -1, end = -1, num = 0;
for (int i = 0; i < s.size(); i++) {
if (s[i] == c) {
if (start == -1) start = i;
end = i;
num++;
}
}
// 2. 两个c中间连续字符、前后字符对应的价值
int midVal = (1 + num) * num / 2;
int leftVal = (1 + start) * start / 2;
int len = s.size() - end - 1;
int rightVal = (1 + len) * len / 2;
int totalVal = leftVal + midVal + rightVal;
return totalVal;
}

int main() {
string S;
while (cin >> S) {
int val1 = findMaxVal(S, '0');
int val2 = findMaxVal(S, '1');
cout << max(val1, val2) << endl;
}
}

@charon2121
Copy link
Contributor

AC 的正确代码可以合并到题解中,如果不知道怎么在题解中并入自己的代码,可以查看提交PR的方法。链接:https://www.programmercarl.com/qita/join.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants