How to optimize the code for 10 power 5 output

The name of the picture


How to optimize the code for 10 power 5 output



Please help me to find out how to optimize this code for 10 to the power 5 output in java. It's show time limit error. Even i try to use HashMap in place of DP array. I tried all the method which i know to optimize this. For bigger output i used long as datatype.


public static void main(String args) throws Exception {
Scanner s = new Scanner(System.in);
int t = s.nextInt();
HashMap<Long, Long> hash = new HashMap<Long, Long>();
for (int i = 0; i < t; i++) {
int n = s.nextInt();
int a = s.nextInt();
int b = s.nextInt();
long val = Long.MAX_VALUE;
if (a == b) {
if (n % 2 == 0) {
int ans = (n / 2) * (n / 2);
val = (a * ans) + (b * ans);
} else {
int ans = n / 2;
val = (a * (ans * ans)) + (b * ((ans + 1) * (ans + 1)));
}
} else {
for (long j = 0; j <= n; j++) {
if (hash.containsKey(j) && hash.containsKey(n - j)) {
long cal = (a * hash.get(j)) + (b * hash.get(n - j));
if (val > cal) {
val = cal;
}
} else {
if (!hash.containsKey(j)) {
hash.put(j, j * j);
}
if (!hash.containsKey(n - j)) {
hash.put(n - j, (n - j) * (n - j));
}
long cal = (a * hash.get(j)) + (b * hash.get(n - j));
if (val > cal) {
val = cal;
}
}
}
}
System.out.println(val);
}
}





javascript !== java
– Nina Scholz
7 hours ago


javascript !== java





what on earth are you trying to do?
– Gyro Gearless
6 hours ago





It looks like the search for the minimum of a*j²+b*(n-j)² for 0<=j<=n.
– Ralf Renz
6 hours ago









By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Stripe::AuthenticationError No API key provided. Set your API key using “Stripe.api_key = ”

CRM reporting Extension - SSRS instance is blank

Keycloak server returning user_not_found error when user is already imported with LDAP