Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Build confidence with an intuition-first walkthrough focused on array fundamentals.
Given an integer array nums and an integer k, modify the array in the following way:
i and replace nums[i] with -nums[i].You should apply this process exactly k times. You may choose the same index i multiple times.
Return the largest possible sum of the array after modifying it in this way.
Example 1:
Input: nums = [4,2,3], k = 1 Output: 5 Explanation: Choose index 1 and nums becomes [4,-2,3].
Example 2:
Input: nums = [3,-1,0,2], k = 3 Output: 6 Explanation: Choose indices (1, 2, 2) and nums becomes [3,1,0,2].
Example 3:
Input: nums = [2,-3,-1,5,-4], k = 2 Output: 13 Explanation: Choose indices (1, 4) and nums becomes [2,3,-1,5,4].
Constraints:
1 <= nums.length <= 104-100 <= nums[i] <= 1001 <= k <= 104Problem summary: Given an integer array nums and an integer k, modify the array in the following way: choose an index i and replace nums[i] with -nums[i]. You should apply this process exactly k times. You may choose the same index i multiple times. Return the largest possible sum of the array after modifying it in this way.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Greedy
[4,2,3] 1
[3,-1,0,2] 3
[2,-3,-1,5,-4] 2
find-subsequence-of-length-k-with-the-largest-sum)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1005: Maximize Sum Of Array After K Negations
class Solution {
public int largestSumAfterKNegations(int[] nums, int k) {
Map<Integer, Integer> cnt = new HashMap<>();
for (int x : nums) {
cnt.merge(x, 1, Integer::sum);
}
for (int x = -100; x < 0 && k > 0; ++x) {
if (cnt.getOrDefault(x, 0) > 0) {
int m = Math.min(cnt.get(x), k);
cnt.merge(x, -m, Integer::sum);
cnt.merge(-x, m, Integer::sum);
k -= m;
}
}
if ((k & 1) == 1 && cnt.getOrDefault(0, 0) == 0) {
for (int x = 1; x <= 100; ++x) {
if (cnt.getOrDefault(x, 0) > 0) {
cnt.merge(x, -1, Integer::sum);
cnt.merge(-x, 1, Integer::sum);
break;
}
}
}
int ans = 0;
for (var e : cnt.entrySet()) {
ans += e.getKey() * e.getValue();
}
return ans;
}
}
// Accepted solution for LeetCode #1005: Maximize Sum Of Array After K Negations
func largestSumAfterKNegations(nums []int, k int) (ans int) {
cnt := map[int]int{}
for _, x := range nums {
cnt[x]++
}
for x := -100; x < 0 && k > 0; x++ {
if cnt[x] > 0 {
m := min(k, cnt[x])
cnt[x] -= m
cnt[-x] += m
k -= m
}
}
if k&1 == 1 && cnt[0] == 0 {
for x := 1; x <= 100; x++ {
if cnt[x] > 0 {
cnt[x]--
cnt[-x]++
break
}
}
}
for x, v := range cnt {
ans += x * v
}
return
}
# Accepted solution for LeetCode #1005: Maximize Sum Of Array After K Negations
class Solution:
def largestSumAfterKNegations(self, nums: List[int], k: int) -> int:
cnt = Counter(nums)
for x in range(-100, 0):
if cnt[x]:
m = min(cnt[x], k)
cnt[x] -= m
cnt[-x] += m
k -= m
if k == 0:
break
if k & 1 and cnt[0] == 0:
for x in range(1, 101):
if cnt[x]:
cnt[x] -= 1
cnt[-x] += 1
break
return sum(x * v for x, v in cnt.items())
// Accepted solution for LeetCode #1005: Maximize Sum Of Array After K Negations
struct Solution;
use std::cmp::Reverse;
use std::collections::BinaryHeap;
impl Solution {
fn largest_sum_after_k_negations(a: Vec<i32>, mut k: i32) -> i32 {
let reverse: Vec<Reverse<i32>> = a.into_iter().map(Reverse).collect();
let mut pq = BinaryHeap::from(reverse);
while k > 0 {
if let Some(min) = pq.pop() {
pq.push(Reverse(-min.0));
}
k -= 1;
}
pq.into_iter().map(|x| x.0).sum()
}
}
#[test]
fn test() {
let a = vec![4, 2, 3];
let k = 1;
assert_eq!(Solution::largest_sum_after_k_negations(a, k), 5);
let a = vec![3, -1, 0, 2];
let k = 3;
assert_eq!(Solution::largest_sum_after_k_negations(a, k), 6);
let a = vec![2, -3, -1, 5, -4];
let k = 2;
assert_eq!(Solution::largest_sum_after_k_negations(a, k), 13);
}
// Accepted solution for LeetCode #1005: Maximize Sum Of Array After K Negations
function largestSumAfterKNegations(nums: number[], k: number): number {
const cnt: Map<number, number> = new Map();
for (const x of nums) {
cnt.set(x, (cnt.get(x) || 0) + 1);
}
for (let x = -100; x < 0 && k > 0; ++x) {
if (cnt.get(x)! > 0) {
const m = Math.min(cnt.get(x) || 0, k);
cnt.set(x, (cnt.get(x) || 0) - m);
cnt.set(-x, (cnt.get(-x) || 0) + m);
k -= m;
}
}
if ((k & 1) === 1 && (cnt.get(0) || 0) === 0) {
for (let x = 1; x <= 100; ++x) {
if (cnt.get(x)! > 0) {
cnt.set(x, (cnt.get(x) || 0) - 1);
cnt.set(-x, (cnt.get(-x) || 0) + 1);
break;
}
}
}
return Array.from(cnt.entries()).reduce((acc, [k, v]) => acc + k * v, 0);
}
Use this to step through a reusable interview workflow for this problem.
Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.
Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.