Hi recently while trying to solve a core Java algorithm question I got trapped into a problem.
Let me explain the puzzle.
There is a series of numbers. where difference between any consecutive
numbers is either a or b. The 1st number of the series is 0. Our code
should compute the last possible numbers given the total count of
elements say n and values of a and b. Constraints: 1 ≤ n, a, b ≤ 1000
Test Case 1.
stdin:
n=3
a=1
b=2
stdout:
2 3 4
Explanation
All possible series for first test case are given below.
0,1,2
0,1,3
0,2,3
0,2,4
Hence the answer 2 3 4.
Test Case 2.
stdin:
n = 4
a = 10
b = 100
stdout:
30 120 210 300
Series with different number of final step for second test cases are
0, 10, 20, 30
0, 10, 20, 120
0, 10, 110, 120
0, 10, 110, 210
0, 100, 110, 120
0, 100, 110, 210
0, 100, 200, 210
0, 100, 200, 300
hence the answer 30 120 210 300
Now the actual bugger. My code computes desired output for less value of n. But when n exceeds say 50 I get
CPU time limit exceeded (core dumped)
Terminated due to timeout
Kindly share if I can improve my approch to compute faster.
Let me share my code:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Solution {
private static List<Integer> listPossibleValues;
private static int maxStone;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
if (1 <= t && t <= 10) {
while (t-- > 0)
getPossibleLastValue(scanner.nextInt(), scanner.nextInt(), scanner.nextInt());
}
}
private static void getPossibleLastValue(int n, int a, int b) {
maxStone = n;
listPossibleValues = new ArrayList<Integer>();
int stone = 0;
getNextStone(stone,0, a, b);
Collections.sort(listPossibleValues);
System.out.println(listPossibleValues.toString().replace("[", "").replace("]", "").replace(",", ""));
}
private static void getNextStone(int stone, int lastValue, int a, int b) {
int newLastA = lastValue + a;
int newLastB = lastValue + b;
stone++;
if (stone < maxStone -1){
getNextStone(stone,newLastA,a,b);
getNextStone(stone,newLastB,a,b);
}
else
{
if(!listPossibleValues.contains(newLastA)){
listPossibleValues.add(newLastA);
}
if(!listPossibleValues.contains(newLastB)){
listPossibleValues.add(newLastB);
}
}
}
}
My testcase sample:
n = 3
a = 1
b = 2
2 3 4
n = 4
a = 10
b = 100
30 120 210 300
n = 9
a = 25
b = 59
200 234 268 302 336 370 404 438 472
n = 18
a = 28
b = 28
476
n = 12
a = 26
b = 35
286 295 304 313 322 331 340 349 358 367 376 385