Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #2218: Maximum Value of K Coins From Piles

In this guide, we solve Leetcode #2218 Maximum Value of K Coins From Piles in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

There are n piles of coins on a table. Each pile consists of a positive number of coins of assorted denominations.

Quick Facts

  • Difficulty: Hard
  • Premium: No
  • Tags: Array, Dynamic Programming, Prefix Sum

Intuition

The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.

A carefully chosen DP state captures exactly what we need to build the final answer.

Approach

Define the DP state and recurrence, then compute states in the correct order.

Optionally compress space once the recurrence is clear.

Steps:

  • Choose a DP state definition.
  • Write the recurrence and base cases.
  • Compute states in the correct order.

Example

Input: piles = [[1,100,3],[7,8,9]], k = 2 Output: 101 Explanation: The above diagram shows the different ways we can choose k coins. The maximum total we can obtain is 101.

Python Solution

class Solution: def maxValueOfCoins(self, piles: List[List[int]], k: int) -> int: n = len(piles) f = [[0] * (k + 1) for _ in range(n + 1)] for i, nums in enumerate(piles, 1): s = list(accumulate(nums, initial=0)) for j in range(k + 1): for h, w in enumerate(s): if j < h: break f[i][j] = max(f[i][j], f[i - 1][j - h] + w) return f[n][k]

Complexity

The time complexity is O(k×L)O(k \times L)O(k×L), and the space complexity is O(n×k)O(n \times k)O(n×k). The space complexity is O(n×k)O(n \times k)O(n×k).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy