MediumNo. 1049

Last Stone Weight II — LeetCode 1049 Python Solution

Topics
Array, Dynamic Programming
Reading time
3 min

The problem

You are given an array of integers stones where stones[i] is the weight of the ith stone. We are playing a game with the stones.

Example

Input
stones = [2,7,4,1,8,1]
Output
1
Explanation
We can combine 2 and 4 to get 2, so the array converts to [2,7,1,8,1] then,

Python solution

PythonSolution
class Solution:
    def lastStoneWeightII(self, stones: List[int]) -> int:
        s = sum(stones)
        m, n = len(stones), s >> 1
        dp = [[0] * (n + 1) for _ in range(m + 1)]
        for i in range(1, m + 1):
            for j in range(n + 1):
                dp[i][j] = dp[i - 1][j]
                if stones[i - 1] <= j:
                    dp[i][j] = max(
                        dp[i][j], dp[i - 1][j - stones[i - 1]] + stones[i - 1]
                    )
        return s - 2 * dp[-1][-1]

Complexity

Time
O(n·m) (typical)
Space · auxiliary
O(n·m)or optimized

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1049. Last Stone Weight II is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
1046Last Stone WeightEasy
1043Partition Array for Maximum SumMedium
1039Minimum Score Triangulation of PolygonMedium
0045Jump Game IIMedium
0053Maximum SubarrayMedium
0055Jump GameMedium

Frequently asked questions

How hard is LeetCode 1049. Last Stone Weight II?

LeetCode 1049. Last Stone Weight II is rated Medium on LeetCode.

What topics does LeetCode 1049. Last Stone Weight II cover?

LeetCode 1049. Last Stone Weight II is tagged Array and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.