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
import java.util.Scanner;
class Minimum_Maximum
{
publicstaticvoid 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[]=newlong[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
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.