Find the N-th Value After K Seconds in Java

Given two integers, n and k. We begin with an array an of n integers at first, such that for every 0 <= i <= n - 1, such that a[i] = 1. We simultaneously update each element after every second so that it is the total of all the elements that occurred before it, plus the element itself. After k seconds, return the value of a[n - 1].

Example 1:

Input:

int n = 4

int k = 5

Output:

The value after k seconds is 56.

Explanation:

As the given n value is 4 hence initialize the array elements of array to [1, 1, 1, 1]. We repeat k times (in this case, five). Based on the cumulative sum of the elements from the previous state, we update the array at each iteration.

SecondState After
0[1,1,1,1]
1[1,2,3,4]
2[1,3,6,10]
3[1,4,10,20]
4[1,5,15,35]
5[1,6,21,56]

Example 2:

Input:

int n = 5

int k = 3

Output:

The value after k seconds is 35.

Explanation:

As the given n value is 5 hence initialize the array elements of array to [1, 1, 1, 1, 1]. We repeat k times (in this case, three). Based on the cumulative sum of the elements from the previous state, we update the array at each iteration.

SecondState After
0[1,1,1,1,1]
1[1,2,3,4,5]
2[1,3,6,10,15]
3[1,4,10,20,35]

Approach: Using Dynamic Programming

The problem is updating an array over a period of several seconds in a particular way. The value of each element in the array is changed to equal the total of all of its predecessors plus itself. The process is comparable to creating a cumulative sum array, in which every iteration causes each member to progressively accumulate values. Finding the value of the array's final element after these modifications is the problem at task.

Algorithm:

Step 1: An array of 𝑛 elements is initialized, with each element set to 1.

Step 2: For every second between 1 and 𝑘.

Step 2.1: Starting with the second entry in the array, update each subsequent element by appending the value of the preceding element.

Step 2.2: The cumulative total is increased by this to that point.

Step 3: To avoid an excess and to keep the values under control, use modulo.

Step 4: After 𝑘 seconds, return the result; the last entry in the array is the desired value.

Implementation:

FileName: NValueKsecsAfter.java

Output:

 
The value after 5 seconds for the given value 4 is: 56   

Complexity Analysis:

The above code's time complexity is O(n×k), where k is the number of seconds and n is the number of elements. Its space complexity is O(n).