Back to Practice Dashboard
Competitive ProgrammingEasy

Maximize the sum of array

Learn how to solve the 'Maximize the sum of array' problem. This detailed resource details brute force and optimized approaches.

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?
Analyze the input constraints. Try sorting first (O(n log n)) or using a hash map/set to track seen elements in O(n) time.
Edge Cases to Watch
  • Empty list or null input variables
  • Single item lists/arrays
  • Extremely large input bounds causing integer or stack overflow

Ready to Solve?

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

Open in Editor