201703-1 分蛋糕

使用一個變量weight來記錄當前小朋友已經拿到的蛋糕的重量,如果weight超過k,那麼weight置0,計數器加一

注意在結束遍歷時,如果weight大於0,那計數器還應再加一

奉上java滿分代碼

import java.util.Scanner;

public class Main{
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        String[] firstLine = scanner.nextLine().split(" ");
        int n = Integer.parseInt(firstLine[0]);
        int k = Integer.parseInt(firstLine[1]);
        int[] numbers = new int[n];
        String[] line = scanner.nextLine().split(" ");
        for(int i = 0; i < n; i++){
            numbers[i] = Integer.parseInt(line[i]);
        }
        scanner.close();

        int weight = 0;
        int count = 0;
        for(int number : numbers){
            weight += number;
            if(weight >= k){
                count++;
                weight = 0;
            }
        }
        count += (weight > 0) ? 1 : 0;
        System.out.println(count);
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章