Greedy Algorithms8 sections · 316 units
Open in Course

Problem - Maximize Sum of Array After K Negations

Flip negatives

Given an array and integer kk, choose an index and negate the value. Do this kk times to maximize the sum. For A=[4,2,3]A = [4,2,3], k=1k = 1, negate nothing (or negate and un-negate). Max sum is 99. For A=[3,1,0,2]A = [3,-1,0,2], k=3k = 3, negate 1-1 three times (or negate it once, then negate 00 twice). Answer is 66.

Think about which elements you should negate and in what order. Constraint: you must use exactly kk negations, even if it means negating the same element multiple times.

If all numbers are positive and kk is odd, you will end up with one negative number. The goal is to minimize the absolute value of that final negative.