1753. Doing Homework
class Solution {
public:
/**
* @param cost: the cost
* @param val: the val
* @return: the all cost
*/
long long doingHomework(vector<int> &cost, vector<int> &val) {
// Write your code here.
long long res = 0;
const int size = cost.size();
if(size == 0){
return res;
}
vector<int> prefixSum(size, 0);
prefixSum[0] = cost[0];
for(int i = 1; i < size; i++){
prefixSum[i] = prefixSum[i - 1] + cost[i];
}
for(int i = 0; i < val.size(); i++){
// search the max num equal or smaller than val[i].
int target = val[i];
int start = 0;
int end = size - 1;
//int flag = 0;
while(start + 1 < end){
int mid = start + (end - start) / 2;
if(prefixSum[mid] <= target){
start = mid;
}
else{
end = mid;
}
}
if(prefixSum[end] <= target){
res += prefixSum[end];
}
else if(prefixSum[start] <= target){
res += prefixSum[start];
}
}
return res;
}
};
Comments
Post a Comment