### 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:
 ``12345678910111213141516171819202122`` ``````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

Alternative code:
 ``1234567891011121314151617181920212223242526`` ``````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;iarr[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.