讨论/《滴滴历届真题汇总》 - 2019 卷 2:魔法权杖强化/
《滴滴历届真题汇总》 - 2019 卷 2:魔法权杖强化
共 1 个回复

TLE 8/10
求大佬指教 贪心+二分

import java.util.Scanner;

class Solution {
    static int n;
    static int m;
    static int[] res;

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        n = in.nextInt();
        res = new int[n];
        m = in.nextInt();
        for (int i = 0; i < n; i++) {
            res[i] = in.nextInt();
        }
        int low = 1000000;
        int high = 0;
        for (int i = 0; i < n; i++) {
            high += res[i];
            low = Math.min(low,res[i]);
        }
        int rs = -1;
        while (low <= high) {
            int mid = (low + high) / 2;
            if (isValid(mid)) {
                rs = Math.max(rs, mid);
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        System.out.println(rs);
    }

    public static boolean isValid(int val) {
        int cnt = 0;
        int cur = 0;
        for (int i = 0; i < n; i++) {
            cur += res[i];
            if (cur < val) {
                cnt++;
                if(cnt > m) return false;
            } else {
                cur = 0;
            }
        }
        return cnt <= m;
    }

}
//
1