Click here to Skip to main content
15,895,423 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How can i optimize it for less than 1 sec

What I have tried:

C#
import java.util.*;

class TestClass {

public static void main(String args[] ) {
    Scanner sc=new Scanner(System.in);
    int n=sc.nextInt();
    int a[]=new int[n];
    int b[]=new int[n];
    for(int i=0;i<n;i++)
    {
        a[i]=sc.nextInt();
        b[i]=sc.nextInt();
    }
    long sum=0;
    for(int i=0;i<n-1;i++)
    {
        for(int j=i+1;j<n;j++)
        {
          sum += Math.abs(a[i]-a[j])*(Math.max(b[i],b[j]));   
        }
    }
    System.out.println(sum);
    }

}
Posted
Updated 18-Dec-16 0:53am
Comments
Patrice T 18-Dec-16 6:28am    
Without knowledge of what is this code, there is not much to do. the code look already optimum.

1 solution

That will never execute under 1 second. There are many things,

1) User input is request, which will be more than seconds in itself.
2) The size is unknown, array manipulation will take a long time.
3) Two loops, even if we improve one, what about second?
4) Math library functions also require some CPU time.

Just one solution, make sure the size of arrays and loops is less than 10 elements. Only then it might work. What I worked,
Java
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package hellojava;

/**
 *
 * @author afzaa
 */
public class HelloJava {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int n = 10; 
        int a[] = new int[n];
        int b[] = new int[n];
        for(int i=0;i<n;i++)
        {
            a[i] = arr[i];
            b[i] = arr[i];
        }
        long sum=0;
        for(int i=0;i<n-1;i++)
        {
            for(int j=i+1;j<n;j++)
            {
              sum += Math.abs(a[i]-a[j])*(Math.max(b[i],b[j]));   
            }
        }
        System.out.println(sum);
    }
}

This program, takes exactly 1 second to execute.
run:
1320
BUILD SUCCESSFUL (total time: 1 second)

See? Just what I said. :)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900