把石头分为若干堆

题目: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;
    }
}
相关文章
相关标签/搜索