|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +# 1561. Maximum Number of Coins You Can Get |
| 4 | +# Medium |
| 5 | +# https://leetcode.com/problems/maximum-number-of-coins-you-can-get |
| 6 | + |
| 7 | +=begin |
| 8 | +There are 3n piles of coins of varying size, you and your friends will take piles of coins as follows: |
| 9 | +* In each step, you will choose any 3 piles of coins (not necessarily consecutive). |
| 10 | +* Of your choice, Alice will pick the pile with the maximum number of coins. |
| 11 | +* You will pick the next pile with the maximum number of coins. |
| 12 | +* Your friend Bob will pick the last pile. |
| 13 | +* Repeat until there are no more piles of coins. |
| 14 | +Given an array of integers piles where piles[i] is the number of coins in the ith pile. |
| 15 | +Return the maximum number of coins that you can have. |
| 16 | +
|
| 17 | +Example 1: |
| 18 | +Input: piles = [2,4,1,2,7,8] |
| 19 | +Output: 9 |
| 20 | +Explanation: Choose the triplet (2, 7, 8), Alice Pick the pile with 8 coins, you the pile with 7 coins and Bob the last one. |
| 21 | +Choose the triplet (1, 2, 4), Alice Pick the pile with 4 coins, you the pile with 2 coins and Bob the last one. |
| 22 | +The maximum number of coins which you can have are: 7 + 2 = 9. |
| 23 | +On the other hand if we choose this arrangement (1, 2, 8), (2, 4, 7) you only get 2 + 4 = 6 coins which is not optimal. |
| 24 | +
|
| 25 | +Example 2: |
| 26 | +Input: piles = [2,4,5] |
| 27 | +Output: 4 |
| 28 | +
|
| 29 | +Example 3: |
| 30 | +Input: piles = [9,8,7,6,5,1,2,3,4] |
| 31 | +Output: 18 |
| 32 | +
|
| 33 | +Constraints: |
| 34 | +3 <= piles.length <= 105 |
| 35 | +piles.length % 3 == 0 |
| 36 | +1 <= piles[i] <= 104 |
| 37 | +=end |
| 38 | + |
| 39 | +# @param {Integer[]} piles |
| 40 | +# @return {Integer} |
| 41 | +def max_coins(piles) |
| 42 | + piles.sort! |
| 43 | + |
| 44 | + j = 0 |
| 45 | + i = piles.length - 2 |
| 46 | + sum = 0 |
| 47 | + |
| 48 | + while i > j do |
| 49 | + sum += piles[i] |
| 50 | + i -= 2 |
| 51 | + j += 1 |
| 52 | + end |
| 53 | + |
| 54 | + sum |
| 55 | +end |
| 56 | + |
| 57 | +# **************** # |
| 58 | +# TEST # |
| 59 | +# **************** # |
| 60 | + |
| 61 | +require "test/unit" |
| 62 | +class Test_max_coins < Test::Unit::TestCase |
| 63 | + def test_ |
| 64 | + assert_equal 9, max_coins([2, 4, 1, 2, 7, 8]) |
| 65 | + assert_equal 4, max_coins([2, 4, 5]) |
| 66 | + assert_equal 18, max_coins([9, 8, 7, 6, 5, 1, 2, 3, 4]) |
| 67 | + end |
| 68 | +end |
0 commit comments