第 93 场双周赛
1.数组中字符串的最大值
Solution
class Solution {
public:
int maximumValue(vector<string>& strs) {
int ans = -1;
for(auto x : strs){
int n = x.size();
int sum = 0;
bool flag = true;
for(int i = 0;i < n;i++){
if(x[i] < '0' || x[i] > '9'){
ans = max(ans,n);
flag = false;
break;
}
sum = sum*10 + x[i]-'0';
}
if(flag) ans = max(ans,sum);
}
return ans;
}
};
2.图中最大星和
Solution
建立图的邻接表,然后按大小排序算就行
class Solution {
public:
int maxStarSum(vector<int>& vals, vector<vector<int>>& edges, int k) {
//建立邻接表
int n = vals.size();
vector<vector<int>> g(n);
for (auto &e : edges) {
if (vals[e[1]] > 0) {
g[e[0]].push_back(vals[e[1]]);
}
if (vals[e[0]] > 0) {
g[e[1]].push_back(vals[e[0]]);
}
}
int ans = INT_MIN;
for (int i = 0; i < n; i++) {
int cur = vals[i];
sort(g[i].begin(), g[i].end(), greater<>());
int upper = min(k, (int)g[i].size());
for (int j = 0; j < upper; j++) {
cur += g[i][j];
}
ans = max(ans, cur);
}
return ans;
}
};
3.青蛙过河 II
Solution
二分答案,看题就能看出
class Solution {
public:
int maxJump(vector<int>& stones) {
auto check = [&](int x, vector<int> &m){
//先跳到最后
vector<bool> book(m.size(),false);
for(int i = 0,j = 1;j < m.size();j++){
while(j < m.size() && m[j] - m[i] <= x) j++;
book[j-1] = true;
i = j-1;
}
book[m.size() - 1] = false;
//从正面跳一遍
for(int i = 0,j = 1;j < m.size(); j++){
while(j < m.size() && book[j]) j++;
if(m[j] - m[i] > x) return false;
i = j;
}
return true;
};
int l = 1, r = stones.back();
while(l < r){
int mid = l + (r - l) / 2;
if(check(mid,stones)){
r = mid;
}else{
l = mid+1;
}
}
return l;
}
};
4.让数组不相等的最小总代价
Solution
class Solution {
public:
long long minimumTotalCost(vector<int>& nums1, vector<int>& nums2) {
long long num = nums1[0],cnt = 0;
vector<int> point;
//跑出众数
for(int i = 0;i < nums1.size();i++){
if(nums1[i] == nums2[i]){
point.push_back(i);
if(cnt == 0) num = nums1[i];
if(num == nums1[i]) cnt++;
else cnt--;
}
}
cnt = 0;
//记录众数数量
for(int i = 0;i < nums1.size();i++){
if(nums1[i] == nums2[i] && num == nums1[i]){
cnt++;
}
}
int n = point.size();
long long ans = 0;
if(cnt >= ceil(n / 2.0)){//超过一半需要从左到右进行选择
ans = accumulate(point.begin(),point.end(),0ll);
cnt = cnt - (n - cnt);
for(int i = 0;i < nums1.size();i++){
if(nums1[i] != nums2[i] && num != nums1[i] && num != nums2[i]){
cnt--;ans += i;
}
if(cnt == 0) break;
}
if(cnt > 0)return -1;
}
else{
ans = accumulate(point.begin(),point.end(),0ll);
}
return ans;
}
};