My issue
hey can anyone explain why we need to take both sides into consideration after sorting if we think greedily sorting in reverse order both the arrays will always gives us the maximum energy why we need to check from right to left too.
My code
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner scn=new Scanner(System.in);
int t=scn.nextInt();
while(t-->0){
int n=scn.nextInt();
int m=scn.nextInt();
int h=scn.nextInt();
int[] cap=new int[n];
int[] map=new int[m];
for(int i=0;i<n;i++){
cap[i]=scn.nextInt();
}
for(int i=0;i<m;i++){
map[i]=scn.nextInt();
}
Arrays.sort(cap);
Arrays.sort(map);
int i=cap.length-1;
int j=map.length-1;
long sum=0;
while(i>=0 && j>=0){
int mcap=map[j]*h;
int z=Math.min(mcap,cap[i]);
sum+=z;
i--;
j--;
}
System.out.println(sum);
}
}
}
Learning course: Greedy Algorithms
Problem Link: CodeChef: Practical coding for everyone