CSES - Array Division

Author: Michael Cao

In this problem, we're asked to divide an array into kk subarrays such that the maximum sum of a subarray is minimized.

Binary Search

Let's begin by making an important observation. First of all, if you can divide an array such that the maximum sum is at most xx, you can also divide the array such that the maximum sum is at most y>xy > x with the same division.

Greedy

Now, given some maximum sum xx, we can check whether a division is possible using a greedy algorithm. If we can divide the array into s<ks < k subarrays, then we can divide it into kk subarrays without increasing the maximum sum of a subarray. Therefore, we can greedily create subarrays as long as the sum of the subarray does not exceed xx, and check if the number of subarrays is k\leq k.

Warning!

Make sure to use long longs to avoid overflow! Implementing the greedy algorithm also requires some caution.

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vi = vector<int>;
#define pb push_back
#define rsz resize
#define all(x) begin(x), end(x)
#define sz(x) (int)(x).size()

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!