Home > Blockchain >  Not getting expected answer using this approach?
Not getting expected answer using this approach?

Time:07-02

I am solving a question on LeetCode , Here is the Link

I got the solution but I wanted to know what wrong I am doing here , There are some testCases below or you can visit the link . A helping attempt is always appreciated from my side.

class Solution {
public:
    static bool comparator(vector<int>&a,vector<int>&b){
        return a[1]>b[1];
    }
    int maximumUnits(vector<vector<int>>& boxTypes, int truckSize) {
        
        sort(boxTypes.begin(),boxTypes.end(),comparator);
        int sum=0;

        for(int i =0;i<boxTypes.size();i  ){
           
            if(truckSize>boxTypes[i][0]){
                sum =boxTypes[i][0] * boxTypes[i][1];
                truckSize= truckSize - boxTypes[i][0];
                
            }else{
                sum  = truckSize * boxTypes[i][1];
                
            }
            
        }
        return sum;
    }
};

TestCases:

 [[1,3],[2,2],[3,1]]

 4
 
 [[5,10],[2,5],[4,7],[3,9]] 

10

Expected:

8                                        
91                                        

OutPut:

8
101

CodePudding user response:

You need to add a break in the else statement. If truckSize <= boxTypes[i][0], we just load truckSize boxes and it will no longer accept any boxes (which means we need to break the for loop and return the result). Otherwise, it will continue the for loop, and try to load the following boxes.

  • Related