1005.K 次取反后最大化的数组和
如果想求经过 K 次取反后最大化的数组和,应该确保每一次取反都对数组和起到 最大化的正向作用 或 最小化的负向作用。即,当数组中存在负数时,将最小的负数取反;当数组中仅存在正数或零时,将最小的正数或零取反。确保每一次取反操作对于数组和都是最优的,进而达到全局最优。
class Solution {
static bool cmp(int a, int b) {
return abs(a) > abs(b);
}
public:
int largestSumAfterKNegations(vector<int> &A, int K) {
sort(A.begin(), A.end(), cmp);
for (int i = 0; i < A.size(); i++) {
if (A[i] < 0 && K > 0) {
A[i] *= -1;
K--;
}
}
if (K % 2 == 1) A[A.size() - 1] *= -1;
int result = 0;
for (int a : A) result += a;
return result;
}
};
因此,我们需要对数组进行排序,这里按照数组绝对值进行降序排列,通过 for 循环判定元素值正负,如果元素为负,则取反,为正,则不操作。如果所有的负数都使用完毕,则对数组最小的元素(排序的最后一个元素)反复取反,这样可以保证最大化对数组和的正向效应和最小化对数组和的负向作用。
134.加油站
全局问题求按照顺序环路行驶一周的出发油站,将问题分解,如果确保每一次加油和出发之后,油箱里仍有省油,则表明最终能环绕一周。
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int curSum = 0;
int totalSum = 0;
int start = 0;
for (int i = 0; i < gas.size(); i++) {
curSum += gas[i] - cost[i];
totalSum += gas[i] - cost[i];
if (curSum < 0) {
start = i + 1;
curSum = 0;
}
}
if (totalSum < 0) return -1;
return start;
}
};
135.分发糖果
class Solution {
public:
int candy(vector<int>& ratings) {
vector<int> candyVec(ratings.size(), 1);
for (int i = 1; i < ratings.size(); i++) {
if (ratings[i] > ratings[i - 1]) candyVec[i] = candyVec[i - 1] + 1;
}
for (int i = ratings.size() - 2; i >= 0; i--) {
if (ratings[i] > ratings[i + 1] ) {
candyVec[i] = max(candyVec[i], candyVec[i + 1] + 1);
}
}
int result = 0;
for (int i = 0; i < candyVec.size(); i++) result += candyVec[i];
return result;
}
};