-3

The following code I wrote in JAVA takes more than 2 seconds to execute in some absurd test cases:

import java.util.*;
public class Main
{
    public static void main(String args[])
{
    Scanner sc= new Scanner(System.in);
    int n= sc.nextLong();
    long a[]= new long[n];
    for(int i=0; i<n; i++)  // Input.
    {
        a[i]= sc.nextInt();
    }

    for(int i=0; i<n-1; i++)  // Sorting(descending order).
    {
        for(int j=0; j<n-i-1; j++)
        {
            if(a[j]<a[j+1])
            {
                long t=a[j];
                a[j]=a[j+1];
                a[j+1]=t;
            }
        }
    }

    int k=1;
    long max=a[0];

    while(k<=n-1)   // Comparing
    {
        long k1=a[k]*(k+1);
        
        if(max<k1)
        {
            max=k1;
        }

        k++;
    }

    System.out.println(max);
    sc.close();
}
}

But the same code written in Python takes less:

n=int(input())
l=[]
for i in range(0,n):
    l.append(int(input()))
l.sort(reverse=True)
k=1;
max=l[0]
while(k<n):
    k1=l[k]*(k+1)
    if(max<k1):
        max=k1
    k=k+1
print(max)

Why? Results after executing the JAVA code in CodeChef

I cannot review the Test cases which have failed.

Leteps
  • 33
  • 3

1 Answers1

2

There is a difference in java and python implementations:
In java you wrote some kind of a bubble sort with complexity O(n^2), here it is:

   for(int i=0; i<n-1; i++)  // Sorting(descending order).
    {
        for(int j=0; j<n-i-1; j++)
        {
            if(a[j]<a[j+1])
            {
                long t=a[j];
                a[j]=a[j+1];
                a[j+1]=t;
            }
        }
    }

And in python you are using built-in sort method, which I think, has complexity of O(n*logn)

l.sort(reverse=True)

That is the reason for time difference. If you'll use Arrays.sort() in java, it probably will fix the problem.

Monsieur Merso
  • 1,459
  • 1
  • 15
  • 18