I have an array of size n+1 where I wish to store the least cost of purchasing n items(i^th index stores cost of i^th item).
There are m different sellers: each seller provides item L to item R (where L,R>=1 and L,R<=n) for a cost of C each.
To create the least cost array I did the following:
for (int i=1; i<=m; i++) {
int L = L of i^th seller
int R = R of i^th seller
int C = selling price of i^th seller
for (int j=L; j<=R; j++) {
if (leastCost[j]==0 || leastCost[j]>C) {
leastCost[j]=C
}
}
Constructing this array is O(n*m) and accessing this array is O(1).
For very large values of n and m, is there a better way to construct the least cost array?
Perhaps a different approach of not storing it in an array and something else so that overall time complexity is reduced?
O(n^2)from. I get O(n * m). Which is completely different. When you consider how many elements you actually need to access (read from), this should be optimal. Unless there is any additional information you have to start with...msellers, andnprices (average). So this isn*m. You need to go through each element at least once, so(n*m)is optimal (unless you have a quantum computer).