classSolution { public: intlargestSumAfterKNegations(vector<int>& a, int k){ sort(a.begin(), a.end()); int idx = 0; while (k && idx < a.size()) { if (a[idx] < 0) { a[idx] = -a[idx]; idx++; k--; } elsebreak; } int ret = 0; if (!k) { for (auto x: a) ret += x; } else { sort(a.begin(), a.end()); if (k % 2) { a[0] = -a[0]; } for (auto x: a) ret += x; } return ret; } };
classSolution { public: intclumsy(int n){ vector<int64> a; int64 last = -n; int t; for (int i = n - 1; i >= 1; i--) { t = (n - i) % 4; if (t == 0) last = i; elseif (t == 1) last *= i; elseif (t == 2) { last /= i; a.push_back(-last); last = 0; } elseif (t == 3) a.push_back(i); } a.push_back(-last); int ret = 0; for (auto x: a) ret += x; return ret; } };