← Home

1561. Maximum Number of Coins You Can Get

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
greedyC++Markdown
156

The trick here is to name the state correctly, then let the implementation follow. For 1561. Maximum Number of Coins You Can Get, the solution in this repository is mainly a greedy solution.

Guide

What?

Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: greedy.

Guide

When?

Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are maxCoins.

Guide

Why?

The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.

  • Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 488 ms, faster than 50.00% of C++ online submissions for Maximum Number of Coins You Can Get.
02//Memory Usage: 53.5 MB, less than 50.00% of C++ online submissions for Maximum Number of Coins You Can Get.
03class Solution {
04public:
05    int maxCoins(vector<int>& piles) {
06        int n = piles.size();
07        
08        sort(piles.rbegin(), piles.rend());
09        
10        int ans = 0;
11        
12        for(int time = 0, pos = 1; time < n/3; ++time){
13            ans += piles[pos];
14            pos += 2;
15        }
16        
17        return ans;
18    }
19};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.