Skip to the content

The flipping spells

Problem

Each flipping spell changes the sign of one rune: a -3 becomes 3, and a 3 becomes -3. The sorceress Ilse has to cast every one of her spells, and she wants the runes to add up to as much as possible.

Write a function that takes runes, a list of integers (at least one; there may be negatives and zeros), and k, how many spells she has, an integer from 0 up. Return an integer: the highest sum that can be left after exactly k flips. She may flip the same rune as many times as she likes; flipping it twice leaves it as it was.

With -4, 2, -1 and 3 and two spells, she flips -4 and -1, and the sum is 4 + 2 + 1 + 3 = 10. With -3 and 5 and three spells, she flips -3 and spends the other two on one rune, there and back: 3 + 5 = 8. With k at 0, the sum stays as it is.

Examples

  • The first example

    [-4, 2, -1, 3], 2 → 10

  • Two left over, there and back

    [-3, 5], 3 → 8

  • No spells

    [-2, 3], 0 → 1

  • The spare one goes back to the same rune

    [-1, 5, 6], 2 → 10

  • More negatives than spells

    [-6, -2, -9, 1], 2 → 14

Besides these, the challenge has hidden tests that are revealed when you submit your solution.

You start with this

Python

def flip(runes, k):
    pass

JavaScript

function flip(runes, k) {
}
Solve this challenge

It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.

More O(n log n) challenges

See all challenges →