HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Calculate difference of indices

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
indicesdifferencecalculate

Problem

The challenge is to reconstruct an n-digit number using the following information:


On each step, you choose an index x from 1 to n. For all indices y (y
y = ax - ay.


You then calculate B1 — sum of all by which are greater
than 0 and B2 — sum of all by which are less than 0.


The answer for this step is B1 - B2.


Input


The first line contains two integers n and m, denoting the number
of digits and number of steps. The second line contains n digits
(without spaces) a1, a2, ..., an.
Each of the next m lines contains a single integer x denoting the index for
the current step.


Output


For each of m steps print single number in a line - answer of the
step.

Can someone please help me optimize this code or provide a better, less time-consuming solution?

```
import java.io.*;
import java.util.*;
public class Chefs
{
//BufferedReader in;
DataInputStream in;
PrintWriter out;
HashMap mymap=new HashMap();
int a[],n,m,b1,b2;
public Chefs()
{
//in=new BufferedReader(new InputStreamReader(System.in));
in=new DataInputStream(System.in);
out=new PrintWriter(System.out,true);
readInput();
calchef();
}
void readInput()
{
try
{
String digit=in.readLine();
String split[]=digit.split("\\s+");
n=Integer.parseInt(split[0]);
m=Integer.parseInt(split[1]);
a=new int[n];

digit=in.readLine();

for(int i=0;i0)
{
b1+=(a[index-1]-a[j]);
}
else
{
b2+=(a[index-1]-a[j]);
}
}
int ans=b1-b2;
out.println(ans);
mymap.put(index,ans);
}
}
catch(Exception e)
{

Solution

1) I would change the inner for loop this way (very little optimization, unlikely it will bring better performance)

int ans=0;
int y=index-1;
for(int j=0; j 0)
        ans += diff;
    else
        ans -= diff;
}


2) You never store ans in the map.

Code Snippets

int ans=0;
int y=index-1;
for(int j=0; j<y; j++)
{
    int diff = a[y] - a[j];

    if(diff > 0)
        ans += diff;
    else
        ans -= diff;
}

Context

StackExchange Code Review Q#46399, answer score: 2

Revisions (0)

No revisions yet.