- Identify the ordered answer range or sorted search domain.
- Write a predicate whose truth changes only once.
- Move the appropriate boundary after each midpoint check and return the final feasible position.
Code notes
- 67 lines of C++ from the credited upstream file minimum-partition-score-ii.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 6 loop blocks detected.
Complexity
Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 long long minPartitionScore(vector<int>& nums, int k) {8 const auto& binary_search = [](auto left, auto right, const auto& check) {9 while (left <= right) {10 const auto& mid = left + (right - left) / 2;11 if (check(mid)) {12 right = mid - 1;13 } else {14 left = mid + 1;15 }16 }17 return left;18 };19 20 const auto& check = [](const auto& l1, const auto& l2, const auto& l3) {21 return (get<1>(l2) - get<1>(l1)) * (get<0>(l2) - get<0>(l3)) < (get<1>(l3) - get<1>(l2)) * (get<0>(l1) - get<0>(l2));22 };23 24 vector<int64_t> prefix(size(nums) + 1);25 const auto& max_lambda = [&]() {26 int64_t mx = 0;27 const auto& total = prefix.back() * (prefix.back() + 1) / 2;28 for (int i = 1; i < size(nums); ++i) {29 const auto& c1 = prefix[i], &c2 = prefix.back() - prefix[i];30 mx = max(mx, total - (c1 * (c1 + 1) / 2 + c2 * (c2 + 1) / 2));31 }32 return mx;33 };34 35 const auto& f = [&](auto l) {36 int64_t dp = 0;37 int cnt = 0;38 deque<tuple<int64_t, int64_t, int>> hull = {{0, 0, 0}};39 for (int i = 0; i < size(nums); ++i) {40 const auto& x = prefix[i + 1];41 while (size(hull) >= 2 && get<0>(hull[0]) * x + get<1>(hull[0]) > get<0>(hull[1]) * x + get<1>(hull[1])) {42 hull.pop_front();43 }44 dp = (get<0>(hull[0]) * x + get<1>(hull[0])) + (x * x + x) / 2 + l;45 cnt = get<2>(hull[0]) + 1;46 const auto& line = tuple(-x, dp + (x * x - x) / 2, cnt);47 while (size(hull) >= 2 && !check(hull[hull.size() - 2], hull[hull.size() - 1], line)) {48 hull.pop_back();49 }50 hull.emplace_back(line);51 }52 return pair(dp, cnt);53 };54 55 for (int i = 0; i < size(nums); ++i) {56 prefix[i + 1] = prefix[i] + nums[i];57 }58 const auto& mx = max_lambda();59 assert(f(mx).second == 1);60 const auto& l = binary_search(static_cast<int64_t>(0), mx, [&](const auto& l) {61 return f(l).second <= k;62 });63 return f(l).first - k * l;64 }65};66 67