Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Dynamic programming

Ordered ways to reach a total

Medium · Target 15 minutes · Dynamic programming · Type asked atMetaGoogle

Given distinct positive integers nums and a target, return the number of ordered sequences of elements of nums (each usable any number of times) that add up to target. Sequences with the same numbers in a different order count separately. The empty sequence makes 0.

Examples

InputOutputWhy
nums = [1,2,3], target = 471111, 112, 121, 211, 22, 13, 31.
nums = [9], target = 30Nothing fits.
nums = [1,2], target = 58The Fibonacci staircase.

Constraints

  • 1 ≤ nums.length ≤ 200
  • 1 ≤ nums[i] ≤ 1000
  • 0 ≤ target ≤ 1000
  • The answer fits in a 64-bit integer

Hints

Hint 1

Let ways[t] be the number of ordered sequences summing to t; ways[0] = 1.

Hint 2

The last element of a sequence summing to t is some x: ways[t] = Σ ways[t − x].

Hint 3

Totals on the outer loop, numbers inside: that is what makes order count.

Where people lose marks

  • Coins-outside loop order, which counts combinations instead.
  • ways[0] = 0.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.