Definitely, we can do better than O (n * m), and the solution is very simple.
Below is the pseudo code to solve this problem:
Construct a MIN-HEAP of the sellers based on their costs c. Construct another array x[1...n] with its each element set to 0 initially. Do the following initializations: count=0 while(count < n) { S = EXTRACT_MIN(Heap) if(count==0) { for(j=SL to SR) { leastCost[j]=Sc ++count x[j]=SR } } else { for(j=SL;j<=SR;++j) { if(x[j]!=0) { i=x[j] and continue; } else { leastCost[j]=Sc ++count x[j]=SR } } } }
Explanation
The best optimization that we can achieve in this task is that we skip all those array indices that are already populated, because they already have the lowest cost.
x auxiliary array : the x array helps us skip all the indexes of arrays that have already been filled, because:
x [i] stores the index j, so ij already has the lowest cost filled by the array, so this is the reason for using the conditional operator:
if(x[i]!=0) { i=x[i] and continue; }
So basically it helps us jump straight to an index that is not populated.
MIN-HEAP . This allows us to find the minimum cost c of all costs present in time O (logm).
Time complexity
Since we are accessing the array of the smallest number no more than n times, therefore, to access the array: O (n)
Heap building takes O (m)
In the worst case, all sellers will contribute to some indices, and m EXTRACT_MIN (Heap) operations will be performed, and each of them takes O (logm) , so the time for this is O (m * logm) .
Therefore, the total time complexity = O (n + mlogm + m) = O (n + mlogm) .
By the way, if I used the C language, I would use struct for Seller and if Java then the class for Seller .Feel is free for any queries.