Ctrl K

Crystals: Spend or Absorb

Medium
A mage earns points with the help of crystals. The crystals' strengths are given in the array crystals, the mage starts with charge energy and 0 points. The mage may perform two actions, any number of times and in any order: - **Spend.** Pick a crystal i that has not been absorbed, provided charge ≥ crystals[i]: the mage gains 1 point and charge drops by crystals[i]. The crystal stays and can be picked again. - **Absorb.** If the mage already has at least one point, pick a crystal i that has not been absorbed: charge grows by crystals[i] and the crystal is gone for good. Return the largest number of points the mage can collect.
Example 1
crystals=[4, 1, 6], charge=1 → 11

Spend 1 on the crystal of strength 1 (1 point, charge 0). Absorb the crystals of 4 and 6 to reach a charge of 10, then spend it on the weak crystal ten more times: 11 points in total.

Example 2
crystals=[5, 3], charge=2 → 0

The charge is too low for any crystal, and absorbing needs at least one point first. The answer is 0.

Example 3
crystals=[3], charge=10 → 3
Constraints
  • 1 ≤ len(crystals) ≤ 10⁵
  • 1 ≤ crystals[i] ≤ 10⁹
  • 0 ≤ charge ≤ 10⁹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTwo Boards Holding Water MediumFewest Jumps to the End MediumReach the Last Cell MediumAs Many Trades as You Like MediumWhere to Start the Lap Medium
loading Python…
Input
crystals=[4, 1, 6], charge=1
Expected
11

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