Hackerrank – Problem description
The problem description – Hackerrank.
Solution
I took k
following numbers and I calculate a product of these k
numbers. Compare the product with actual maximum. Print the maximum if there are no more k
following numbers.
I created solution in:
All solutions are also available on my GitHub profile.
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
import java.util.Scanner; public class LargestProduct { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int tests = scanner.nextInt(); for (int i = 0; i < tests; i++) { int n = scanner.nextInt(); int k = scanner.nextInt(); String number = scanner.next(); long max = 0; for (int j = 0; j < n - k; j++) { long product = 1; for (int l = j; l < j + k; l++) { product *= Integer .parseInt(String.valueOf(number.charAt(l))); } if(product > max) { max = product; } } System.out.println(max); } scanner.close(); } } |