把石頭分爲若干堆

題目:n塊石頭分爲若干堆放在一條直線,要求每堆至少有一塊石頭,相鄰兩堆數目不一樣。求全部的分堆方法中,堆中石頭大於k的最大的次數。java

思路:貪心算法算法

代碼:spa

import java.util.Scanner;

public class Main2 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int k = sc.nextInt();

        System.out.println(helper(n, k));
    }

    public static int helper(int n, int k) {
        if (k > n) return 0;
        int res = 0;
        int flag = 0;
        while (n > 0) {
            if (n-k-flag >= 0) {
                res++;
                n = n - k - flag;
                flag = 1 - flag;
            } else break;
        }

        return res;
    }
}
相關文章
相關標籤/搜索