← Uber bank

Uber · Question 74 · Dynamic Programming

Burst Balloons

Dynamic ProgrammingPythoncode⏱ O(n³)💾 O(n²)
Product-based

Problem

Given n balloons each with a number, burst them to maximize coins. Bursting balloon i gives nums[left] * nums[i] * nums[right].

Approach

DP on intervals: choose k as last balloon to burst in range (i, j) and solve recursively.

Time O(n³)Space O(n²)

How it works

  1. 1Pad with virtual 1-balloons at both ends.
  2. 2dp[left][right] = best coins strictly inside.
  3. 3Try each balloon as the last burst in the interval.

Sample input / output

Input:
4
3 1 5 8
Output:
167

Constraints

1 <= n <= 300; 0 <= nums[i] <= 100.

Solution — read it, then walk it

Time O(n³)Space O(n²)Loops 3Branches 1Returns 1source · Python
Scroll sideways for wide charts — the view follows the active step.
↻ repeat↻ repeat↻ repeatyesnoSTARTnumsnums = [1] + nums + [1]n = len(nums)dp = [[0] * n for _ inrange(n)]for length in range(2,n)for left in range(n -length)right = left + lengthfor k in range(left +1, right)dp[left][right] =max(dp[left][right],dp[left][k] + nums[left] …RETURN dp[0][n - 1]DEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)n = int(next(it))nums = [int(next(it)) for _in range(n)]print(maxCoins(nums))if __name__ =="__main__"main()END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/20

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits