Ctrl K

A Haul That Splits Three Ways

Medium
Three friends found bags of coins: bag i holds values[i] coins. A bag can't be opened, so each one is either taken whole or left behind. The friends want to share the haul equally, so the total number of coins in the bags they take must be divisible by 3. Return the largest possible number of coins. Taking no bags at all is allowed, in which case the answer is 0.
Example 1
values=[5, 7, 2, 9] → 21

All bags together hold 23, which leaves a remainder of 2 when divided by 3. Leaving out the bag with 2 is cheapest, which leaves 21.

Example 2
values=[4, 4, 4, 1] → 12

The total is 13 with a remainder of 1. Leaving out the bag with 1 gives 12, that is 4 each.

Example 3
values=[1, 1] → 0

Neither 1 nor 2 splits evenly three ways, so it is best to take nothing and the answer is 0.

Constraints
  • 1 ≤ len(values) ≤ 4 · 10⁴
  • 1 ≤ values[i] ≤ 10⁴
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsFewest Meetings to Cancel MediumLongest Chain of Segments MediumStrongest Product Team MediumBreaking a Chocolate Bar MediumBiggest Number Divisible by Three Hard
loading Python…
Input
values=[5, 7, 2, 9]
Expected
21

Run checks the first 3 tests in your browser. Submit checks all 130 tests on the server, hidden ones included.