• [LeetCode] 1561. Maximum Number of Coins You Can Get


    There are 3n piles of coins of varying size, you and your friends will take piles of coins as follows:

    • In each step, you will choose any 3 piles of coins (not necessarily consecutive).
    • Of your choice, Alice will pick the pile with the maximum number of coins.
    • You will pick the next pile with maximum number of coins.
    • Your friend Bob will pick the last pile.
    • Repeat until there are no more piles of coins.

    Given an array of integers piles where piles[i] is the number of coins in the ith pile.

    Return the maximum number of coins which you can have.

    Example 1:

    Input: piles = [2,4,1,2,7,8]
    Output: 9
    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.
    Choose the triplet (1, 2, 4), Alice Pick the pile with 4 coins, you the pile with 2 coins and Bob the last one.
    The maximum number of coins which you can have are: 7 + 2 = 9.
    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.
    

    Example 2:

    Input: piles = [2,4,5]
    Output: 4
    

    Example 3:

    Input: piles = [9,8,7,6,5,1,2,3,4]
    Output: 18

    你可以获得的最大硬币数目。

    有 3n 堆数目不一的硬币,你和你的朋友们打算按以下方式分硬币:

    每一轮中,你将会选出 任意 3 堆硬币(不一定连续)。
    Alice 将会取走硬币数量最多的那一堆。
    你将会取走硬币数量第二多的那一堆。
    Bob 将会取走最后一堆。
    重复这个过程,直到没有更多硬币。
    给你一个整数数组 piles ,其中 piles[i] 是第 i 堆中硬币的数目。

    返回你可以获得的最大硬币数目。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/maximum-number-of-coins-you-can-get
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    思路是排序 + two pointer。这道题我们必须排序,否则是拿不到次多的那一堆的。排序完之后,我们用左右两个指针逼近中间,左指针 i 指向的是每次选取的三堆硬币中最少的,右指针 j 指向的是每次选取的三堆硬币中最多的,j - 1 指向的是次多的。要选取的次数是piles.length / 3。

    时间O(nlogn)

    空间O(1)

    Java实现

     1 class Solution {
     2     public int maxCoins(int[] piles) {
     3         Arrays.sort(piles);
     4         int len = piles.length;
     5         int count = len / 3;
     6         int res = 0;
     7         int i = 0;
     8         int j = len - 1;
     9         while (i < j && count != 0) {
    10             if (j - 1 >= i) {
    11                 res += piles[j - 1];
    12                 count--;
    13             }
    14             i++;
    15             j -= 2;
    16         }
    17         return res;
    18     }
    19 }

    LeetCode 题目总结

  • 相关阅读:
    Java数据处理,Map中数据转double并取小数点后两位
    19年7月份面试7家公司,整理的java面试题(答案自行百度解决,也是个学习的过程)
    2019阿里云面试题,竟然现场敲代码,现在的企业越来越实在了
    解决win10状态栏的搜索框无法搜索本地应用或无反应
    sql,按照时间排序,取前N条
    List数组排序
    阿里云的maven仓库 地址
    hashcode相等两个类一定相等吗?equals呢?相反呢?
    杂记
    java排序
  • 原文地址:https://www.cnblogs.com/cnoodle/p/14444711.html
Copyright © 2020-2023  润新知