【华为机考题】最少任务处理时常

问题描述

假设有一个机器,此机器每秒最大处理任务数量为N,现给定一个数组M,其长度大小为len, 表示len秒内,树组各个值表示该时刻所接受的任务数量。如下例所示:

输入:3 5 [1,2,3,4,5]
输出:6

解释:机器每秒能处理的最大任务数为3,在5秒内有【1,2,3,4,5】的任务数来请求执行,机器如果要全部处理该任务,至少需要6秒种时间。


代码解析

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner in = new Scanner(System.in);
        int max = Integer.parseInt(in.nextLine());
        int len = Integer.parseInt(in.nextLine());
        String task = in.nextLine();
        in.close();
        String[] newTask = task.split(" ");
        // 当前任务数, i 时间
        int cur = 0, i = 0;
        do {
    
    
            if (i < len) {
    
    
                cur += Integer.parseInt(newTask[i]);
            }
            if (cur <= max) {
    
    
                cur = 0;
            } else {
    
    
                cur -= max;
            }
            i++;
        } while (cur > 0 || i < len);
        System.out.println(i);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_44503987/article/details/126139049