Skip to the content

Mansa Musa's bags of gold

Problem

Mali, 1324. Before setting out for Mecca, Mansa Musa lays a row of bags of gold in front of two griots of his court, Kouyaté and Diabaté, and offers them a game. Taking turns, starting with Kouyaté, each one takes a bag from one of the two ends of the row, the left one or the right one, until none are left. Each keeps what he took. Both are clever: each plays to take home as much as he can, knowing the other does the same.

Write a function that takes bags, a list of whole numbers from 1 up with the coins in each bag, in the order of the row (at most 12 bags; it may be empty). Return a whole number: how many coins Kouyaté takes home if both play as well as they can.

With [3, 9, 1, 2]: if Kouyaté takes the bigger end, the 3, he leaves the 9 for Diabaté and ends up with 5. He is better off taking the 2: whatever Diabaté takes, the 9 is left at one end for Kouyaté, who gets 2 + 9 = 11. With [5, 3, 7, 10] he gets 15: he takes the 10, Diabaté the 7, he the 5 and Diabaté the 3. With no bags, 0.

Examples

  • The example

    [3, 9, 1, 2] → 11

  • The second example

    [5, 3, 7, 10] → 15

  • An odd number of bags

    [1, 5, 2] → 3

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

You start with this

Python

def best_haul(bags):
    pass

JavaScript

function bestHaul(bags) {
}
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(2ⁿ) challenges

See all challenges →