It has been a week or so since I tried a challenge in HackerRank. Between work and holidays not much spare time available. BTW Happy Holidays!!!
The URL for the challenge follows: https://www.hackerrank.com/challenges/filling-jars?utm_campaign=challenge-recommendation&utm_medium=email&utm_source=24-hour-campaign
Before proceeding reading this blog I would suggest to go to the web site and solve it on your own.
Suspecting that in most cases the obvious approach is not the correct one, I tried using an array of jars. The constraints and Need Help link provided a clear indication that it would time out. Using BigIntegers in Java helped, but the proper approach (as suggested by the Need Help link) allowed me to solve the challenge.
From the console of the Eclipse IDE the test data follows:
5 3
1 2 100
2 5 100
3 4 100
160
Following is my Java 8 solution:
import java.math.BigInteger;
import java.util.Scanner;
class Jars {
// **** *****
BigInteger N = BigInteger.ZERO;
BigInteger sumTotal = BigInteger.ZERO;
/*
* constructor
*/
public Jars(int N) {
this.N = BigInteger.valueOf((long)N);
}
/*
* compute average number of candies
*/
public long average() {
return (long)this.sumTotal.divide(this.N).doubleValue();
}
/*
* update sum
*/
public void updateSum(int a, int b, int candy) {
BigInteger sum = BigInteger.valueOf((long)b – (long)a + (long)1);
sum = sum.multiply(BigInteger.valueOf((long)candy));
this.sumTotal = this.sumTotal.add(sum);
}
}
public class Solution {
/*
* test code
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int M = sc.nextInt();
Jars myJars = new Jars(N);
for (int m = 0; m < M; m++) {
int a = sc.nextInt();
int b = sc.nextInt();
int k = sc.nextInt();
myJars.updateSum(a, b, k);
}
System.out.println(myJars.average());
sc.close();
}
}
As you can see there is no need to use an array of jars.
If you have comments or questions regarding this or any other entry in this blog, please do not hesitate and send me an email. I will not disclose your name unless you explicitly allow me.
John
john.canessa@gmail.com
Follow me on Twitter: @john_canessa