I feel that the test case 5 of the problem is wrong as it is showing the output 12 whereas the output should have been 15. If anyone who has solved it can check my code.
import java.util.Arrays; import java.util.Scanner; public class A176 {
static class commodity{ int q; int profit; commodity(int q,int profit){ this.q = q; this.profit = profit; } } public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int m = s.nextInt(); int k = s.nextInt(); int cost[][] = new int[n][m]; int sell[][] = new int[n][m]; int q[][] = new int[n][m]; for(int i=0;i<n;i++){ String str = s.next(); for(int j=0;j<m;j++){ cost[i][j] = s.nextInt(); sell[i][j] = s.nextInt(); q[i][j] = s.nextInt(); } } commodity[][] profit = new commodity[n][m]; //setting up the profit 2D array. for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ int c = cost[i][j]; int quantity = q[i][j]; int max = Integer.MIN_VALUE; System.out.println(m); for(int l=0;l<n;l++){ if(l==i) continue; if(sell[l][j]-c>max){ max = sell[l][j]-c; } } if(max>0) profit[i][j] = new commodity(quantity,max); else profit[i][j] = new commodity(quantity,0); } } for(commodity[] a: profit ){ Arrays.sort(a,(p1,p2) -> p2.profit-p1.profit); } Integer[] finalArray = new Integer[n]; for(int i=0;i<n;i++){ int req = k; int total = 0; for(int j=0;j<m;j++){ int p = profit[i][j].profit; int r = profit[i][j].q; if(r<=req){ total += p*r; req -= r; }else{ total += p*req; break; } } finalArray[i] = total; } Arrays.sort(finalArray); System.out.println(finalArray[finalArray.length-1]); }
}