I am coming from this thread: CHEAPEST cost of intervals to cover the target interval
In short, we have a certain target interval and then some other secondary intervals, with the goal of covering the target interval with the CHEAPEST possible set of secondary intervals, and printing the cost.(read other thread for more detail and image explanation)
I moved on to the implementation of the solution using the logic provided as an answer to my question. (https://stackoverflow.com/a/75727860/21392225)
I sorted the secondary intervals by endpoint, and discard the ones that don't overlap the target interval. Then, I built an array (x,cost), where x is the endpoint and cost is the minimum cost to cover the target up to that endpoint. The cost is found using binary search on the array that has been built so far.
code:
void solve(vector<Interval>& intervals, int targetStart, int targetEnd) {
// Sort intervals by endpoint and remove non-overlapping intervals
sort(intervals.begin(), intervals.end(), compareIntervals);
auto it = remove_if(intervals.begin(), intervals.end(),
[&](Interval& i) { return i.start > targetEnd || i.end < targetStart; });
intervals.erase(it, intervals.end());
// array of endpoints and cost
vector<pair<int, int>> endpointCosts;
endpointCosts.push_back({ targetStart, 0 });
for (auto& interval : intervals) {
int lo = 0, hi = endpointCosts.size() - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (endpointCosts[mid].first == interval.start) {
cost = endpointCosts[mid].second;
}
else if (endpointCosts[mid].first < interval.start) {
lo = mid + 1;
}
else {
hi = mid - 1;
}
}
return -1;
std::cout << cost << "\n";
if (cost == -1) {
std::cout << endpointCosts.back().second << "\n";
cost = endpointCosts.back().second;
}
endpointCosts.push_back({ interval.end, cost + interval.cost });
}
// Calculate minimum cost
int minCost = binarySearch(endpointCosts, targetEnd);
cout << "Minimum cost to cover target interval [" << targetStart << ", " << targetEnd << "]: " << minCost << endl;
}
I'm having difficulties in making it so that when a cheaper interval covers the same part of the target as a more expensive interval (20 instead of 30 in the example image from the other thread). If someone has any ideas or can criticize the entire approach itself and has a better recommendation, I would love to hear from you and learn