首先,您需要了解,在这个竞争激烈的问题中,您永远无法学习 C++。相反,你的 C++ 会变得更糟。
接下来,在所有这些问题中,作者已经通过在约束中提供大量数字来给你一个强有力的暗示。这是一个强烈的信息。不要使用蛮力方法开始编码。想出一个聪明的解决方案。
先思考,再思考,再做最后的思考,开发出好的算法。
任务是使尽可能多的值为正数。
有了手头的问题,您将看到可以通过将给定的操作应用到您想要的任何位置来移动负号。示例:让字母为正整数。然后就可以变形了:
a -b c d to
-a b c d or to
a b -c d or to
a b -c d and then a b c -d
应该明白。
如果您有偶数个负数,您可以消除其中的 2 个,方法是将负号移到另一个负号下方,然后使两个值都为正数。这种机制也适用于数组中更多的负偶数。
第一个结论:具有偶数个负数的数组与所有数都为正数的数组相同。我们可以将所有的绝对值相加得到结果。
如果我们有奇数个负数,我们可以将符号移动到我们想要的任何位置,并且可以消除除负值之外的所有负数。因为总和必须是最大值,所以负值必须是最小值,因为它会被减去。所以首先,我们消除尽可能多的负数,然后我们将负号移到最小的绝对值。
现在我们进一步思考:
我们需要找出负值的计数。如果是偶数,我们可以简单地将所有值的绝对值相加并得到结果。对于奇数,我们需要找到最小的绝对值并减去它。
我们可以有这样的想法,读取std::vector 中的所有值,然后计数、计算等等。但不需要。我们可以在读取输入的过程中做到这一点。我们检查到目前为止的最小值,看看总的负数是奇数还是偶数。我们在阅读过程中对所有绝对值求和。如果我们知道最后是奇数,那么我们将最小的数减去两次(因为我们已经添加了它)。
程序可能如下所示:
#include <iostream>
#include <cmath>
#include <limits>
int main() {
// Get the number of test values
size_t numberOfTestValues{};
std::cin >> numberOfTestValues;
// Here we will indicate, if the number of negatives is odd or even
bool oddNumberOfSignedValues{ false };
// This will be the result, the running sum
long sum{};
// This is the smallest value given
long smallestValue{std::numeric_limits<long>::max()};
// Read as many values as specified
for (size_t i{}; i < numberOfTestValues; ++i) {
// Read the vale
long value{};
std::cin >> value;
// Check, if we have now, at this moment, an odd or even number of negatives
if (value < 0) oddNumberOfSignedValues = not oddNumberOfSignedValues;
value = std::abs(value);
// Check for a new smallest value
if (value < smallestValue) smallestValue = value;
// Accumulate
sum += value;
}
// In case necessary (count of negatives was odd) subtract smallest number
if (oddNumberOfSignedValues) sum = sum - smallestValue - smallestValue;
// Show result to use
std::cout << sum << '\n';
return 0;
}
这将降低复杂性。