FunctionRacerProblemsRace

Sum of the Last k

BeginnerDynamic programmingPython, JavaScript, TypeScript, Java, C++

A sequence starts with k ones. Every later term is the sum of the k terms right before it. With k = 2 this gives 1, 1, 2, 3, 5, 8, and with k = 3 it gives 1, 1, 1, 3, 5, 9, 17.

Return term number n of the sequence, counting the first term as number 0.

Example 1

n 5
k 3
returns 9

With three ones to start: 1, 1, 1, 3, 5, 9. Term 5 is 9.

Example 2

n 1
k 4
returns 1

Term 1 is still one of the starting ones.

Example 3

n 9
k 1
returns 1

With k = 1 every term just repeats the one before it.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Dynamic programming problems