# Help me in solving MOONSOON problem

### 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

when you’re sorting elements for a problem, you might consider both ascending (smallest to largest) and descending (largest to smallest) orderings because the best solution might require looking at the problem from both directions. Sometimes, choosing the largest values first is the best strategy, but in other cases, taking smaller values first might lead to a better overall result. It depends on the specific problem and its requirements, so it’s important to be open to different sorting orders to find the optimal solution.