Time Limit Exceeded - Explanation needed

Select a pair of adjacent integers and remove the larger one of these two. This decreases the array size by 1. Cost of this operation will be equal to the smaller of them.
Example
Input
2
2
3 4
3
4 2 5

Output
3
4

Here is my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.*;
public class Main {
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        int t=sc.nextInt();
        for(int i=0;i<t;i++)
        {
        	int n=sc.nextInt();
                int min=Integer.MAX_VALUE;
        	for(int j=0;j<n;j++)
        	{
        		int temp=sc.nextInt();
        		if(temp<min)
        		{
        		min=temp;
        		}
        	}
        	System.out.println(min*(n-1));
        }
    }
}

Alternative code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import java.util.Scanner;
 
class Minimum_Maximum 
{
	public static void main(String[] args) 
	{
		Scanner scan=new Scanner(System.in);
		int test=scan.nextInt();
		for(int t=1;t<=test;t++)
		{
			long min=Integer.MAX_VALUE;
			int n=scan.nextInt();
			long arr[]=new long[n];
			
			for(int i=0;i<n;i++)
			{
				arr[i]=scan.nextInt();
				if(min>arr[i])
					min=arr[i];
			}
			
 
			System.out.println(min*(n-1));
		}
	}
} 



This question was asked in code chef , Now my question is when i tried to submit my first code it showed TIME LIMIT EXCEPTION. whereas the alternative code ran successfully under the specified time limit.
Time limit specified was under 0.54 s
Clarify what is the reason for faster execution in the alternative coding
Last edited on
wrong language :)

not sure about J .... in C++ I would have guessed the 2nd to be slower due to calling new in a loop which is wasteful (call it once up front if possible, and it looks like it would be possible here) but better yet, eliminate dynamic memory entirely (also looks possible here). But those are c++ tweaks, java is different.



Here is the problem.

 
int min=Integer.MAX_VALUE;


The assignment works, but the eventual answer is too big for this data type.

Last edited on
Topic archived. No new replies allowed.