Maximize Sum After K Negations
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 0
Given an integer array nums and an integer k, you must perform exactly k operations, each replacing some
nums[i] with -nums[i] (the same index may be chosen repeatedly). Return the maximum possible sum of the array
afterwards.
Examples
| nums | k | result |
|---|---|---|
[4, 2, 3] | 1 | 5 |
[3, -1, 0, 2] | 3 | 6 |
[2, -3, -1, 5, -4] | 2 | 13 |
Example 2 — flip -1, then spend the remaining two flips on 0.
Efficiency
This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.
Function signature
solution(nums: int[], k: int) → long
Constraints
-
nums.length -
nums[i] -
k - The answer may exceed the 32-bit range.
Expected complexity
- Time
- O(N log N)
- Space
- O(1)
Examples
| nums | k | Expected |
|---|---|---|
[4,2,3] | 1 | 5 |
[3,-1,0,2] | 3 | 6 |
[2,-3,-1,5,-4] | 2 | 13 |
Hint
Hint
The best flip is always the smallest (most negative) value: sort, then turn negatives positive from the smallest up. Flipping the same element twice changes nothing, so any remaining flips only matter through their parity: if an odd number is left, spend it on the element with the smallest absolute value. Performing up to flips one by one exceeds the time limit.
Time limits per language
| Language | Efficiency time limit | |
|---|---|---|
| C (GCC, gnu17) | 200 ms | estimated |
| C++ (GCC, gnu++23) | 200 ms | derived |
| Python 3.13 | 1000 ms | derived |
| Java 25 | 1196 ms | derived |
| Kotlin 2.4 (JVM) | 1400 ms | estimated |
| C# 14 (.NET 10) | 1400 ms | estimated |
Test groups
| Group | Weight | Tests | Visibility |
|---|---|---|---|
| sample | 0 | 3 | inputs and outputs |
| correctness | 40 | 13 | verdict only |
| performance | 60 | 3 | verdict only |