Competitive ProgrammingEasy

Maximize the sum of array

Detailed guide and Python implementation for the 'Maximize the sum of array' problem.

Problem Statement

Easy

Write a function maximize_sum(arr, k) that returns the maximum possible sum of the array after performing exactly k negations. In each negation, you must choose an element and replace it with its negative value. You can negate the same element multiple times.

Constraints
  • 1 <= len(arr) <= 10^5
  • 1 <= k <= 10^5
  • -10^4 <= arr[i] <= 10^4

Examples

Example 1
Input
maximize_sum([-2, 0, 5, -1, 2], 4)
Output
10
Explanation

Negate -2 to 2, -1 to 1. The remaining 2 negations can be performed on 0. The array becomes [2, 0, 5, 1, 2], summing to 10.

Example 2
Input
maximize_sum([3, -1, 0, 2], 3)
Output
6
Explanation

Negate -1 to 1. The remaining 2 negations are performed on 0. Sum is 3 + 1 + 0 + 2 = 6.

Need a Hint?
Consider using Greedy-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.