力扣练习题目——Minimum Time to Complete Trips

给定一个表示每辆公交车完成一次旅行所需时间的数组time和一个总旅行数totalTrips,问题求解所有公交车至少完成totalTrips次旅行的最短时间。通过动态规划方法,找到一个阈值使得所有公交车在该时间点上能完成至少totalTrips次旅行。
摘要由CSDN通过智能技术生成

Minimum Time to Complete Trips

You are given an array time where time[i] denotes the time taken by the ith bus to complete one trip.

Each bus can make multiple trips successively; that is, the next trip can start immediately after completing the current trip. Also, each bus operates independently; that is, the trips of one bus do not influence the trips of any other bus.

You are also given an integer totalTrips, which denotes the number of trips all buses should make in total.

Return the minimum time required for all buses to complete at least totalTrips trips.

 

Example 1:

Input: time = [1,2,3], totalTrips = 5
Output: 3
Explanation:
- At time t = 1, the number of trips completed by each bus are [1,0,0]. 
  The total number of trips completed is 1 + 0 + 0 = 1.
- At time t = 2, the number of trips completed by each bus are [2,1,0]. 
  The total number of trips completed is 2 + 1 + 0 = 3.
- At time t = 3, the number of trips completed by each bus are [3,1,1]. 
  The total number of trips completed is 3 + 1 + 1 = 5.
So the minimum time needed for all buses to complete at least 5 trips is 3.

Example 2:

Input: time = [2], totalTrips = 1
Output: 2
Explanation:
There is only one bus, and it will complete its first trip at t = 2.
So the minimum time needed to complete 1 trip is 2.

 

Constraints:

  • 1 <= time.length <= 10^5
  • 1 <= time[i], totalTrips <= 10^7

题解

经过对题目的分析可知,题目要求一个最小阈值,这个最小的阈值能够满足下面的条件:time%5Bi%5D%7D%3E%3DtotalTrips

代码

class Solution {
public:
    int n,c;
    vector<int>a;
    bool isok(long long s){
        long long sum=0;
        for(int i=0;i<n;i++){
            sum+=s/a[i];
        }
        return sum>=c;
    }
    long long minimumTime(vector<int>& time, int totalTrips) {
        n=time.size();
        for(int i=0;i<n;i++){
            a.push_back(time[i]);
        }
        c=totalTrips;
        long long MAX=0;
        for(int i=0;i<n;i++){
            MAX=max(MAX,(long long)time[i]);
        }
        MAX*=totalTrips;
        long long l=0,r=MAX,mid,ans;
        while(l<=r){
            mid=l+(r-l)/2;
            if(isok(mid))
                ans=mid,r=mid-1;
            else
                l=mid+1;
        }
        return ans;
    }
};

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值