/**
1753 · Doing Homework
Algorithms
Medium
Accepted Rate
38%
DescriptionSolutionNotesDiscussLeaderboard
Description
For n people, each of them needs to do m jobs independently.
The i job takes cost[i] time. Since each person’s free time is different, the i person has val[i] time, which means that the total time for his jobs will not exceed val[i]. Everyone starts with the first job, then the 2nd, the 3rd… Now, you need to figure out how much time they spend.
1<=n<=100000
1<=m<=100000
1<=val[i]<=100000
1<=cost[i]<=100000
Example
Example 1:
Given cost=[1,2,3,5]
,val=[6,10,4]
, return 15
.
Input:
[1,2,3,5]
[6,10,4]
Output:
15
Explanation:
The first person can complete the 1st job, the 2nd job, the 3rd job, 1+2+3<=6.
The second person cancomplete the 1st job, the 2nd job, the 3rd job, and cannot complete the 4th job, 1+2+3<=10, 1+2+3+5>10.
The third person can complete the 1st job, the 2nd job, and cannot complete the 3rd job, 1+2<=4, 1+2+3>4.
1+2+3+1+2+3+1+2=15, returning 15.
Example 2:
Given cost=[3,7,3,2,5]
,val=[10,20,12,8,17,25]
, return 78
.
Input:
[3,7,3,2,5]
[10,20,12,8,17,25]
Output:
78
Explanation:
The first person can complete the 1st job, the 2nd job, 3 + 7<=10.
The second person cancomplete the 1st job, the 2nd job, the 3rd job, the 4th job,the 5th job, 3+7+3+2+5<=20
The third person can complete the 1st job, the 2nd job, and cannot complete the 3rd job, 3+7<=12,3+7+3>12.
The forth person can complete the 1st job, and cannot complete the 2nd job, 3<=8,7+3>8.
The fifth person can complete the 1st job, the 2nd job, the 3rd job, the 4th job, and cannot complete the 5th job,3+7+3+2<=17,3+7+3+2+5>17.
The sixth person cancomplete the 1st job, the 2nd job, the 3rd job, the 4th job,the 5th job, 3+7+3+2+5<=25
3+7+3+7+3+2+5+3+7+3+3+7+3+2+3+7+3+2+5=78, returning 78.
Tags
Recommend Courses
https://www.it610.com/article/1305865594712657920.htm
https://www.lintcode.com/problem/1753/
*/
/**
* @param cost: the cost
* @param val: the val
* @return: the all cost
*/
func doingHomework (cost []int, val []int) int64 {
// Write your code here.
var sums = make([]int, len(cost))
var sum int = 0
for i := 0; i < len(cost); i++ {
sum += cost[i]
sums[i] = sum
}
var res int64 = 0
for i := 0; i < len(val); i++ {
var va int64 = search(sums, val[i])
if va != -1 {
res += va
}
}
return res
}
func search(sums []int, target int) int64 {
if target >= sums[len(sums) - 1] {
return int64(sums[len(sums) - 1])
}
if target < sums[0] {
return -1
}
var l, r int = 0, len(sums) - 1
for {
if l >= r {
break
}
var mid int = l + (r - l) >> 2
if sums[mid] <= target && sums[mid + 1] > target {
return int64(sums[mid])
} else if sums[mid] > target && sums[mid - 1] <= target {
return int64(sums[mid - 1])
} else if sums[mid] < target {
l = mid + 1
} else {
r = mid - 1
}
}
return -1
}