LeetCode-in-Java

3814. Maximum Capacity Within Budget

Medium

You are given two integer arrays costs and capacity, both of length n, where costs[i] represents the purchase cost of the ith machine and capacity[i] represents its performance capacity.

You are also given an integer budget.

You may select at most two distinct machines such that the total cost of the selected machines is strictly less than budget.

Return the maximum achievable total capacity of the selected machines.

Example 1:

Input: costs = [4,8,5,3], capacity = [1,5,2,7], budget = 8

Output: 8

Explanation:

Example 2:

Input: costs = [3,5,7,4], capacity = [2,4,3,6], budget = 7

Output: 6

Explanation:

Example 3:

Input: costs = [2,2,2], capacity = [3,5,4], budget = 5

Output: 9

Explanation:

Constraints:

Solution

public class Solution {
    public int maxCapacity(int[] costs, int[] capacity, int budget) {
        int[] mxCap = new int[budget];
        int maxCap = 0;
        for (int i = 0; i < costs.length; i++) {
            int cost = costs[i];
            int cap = capacity[i];
            if (cost >= budget) {
                continue;
            }
            maxCap = Math.max(maxCap, cap);
            if (cost * 2 < budget) {
                maxCap = Math.max(maxCap, mxCap[cost] + cap);
            }
            if (cap > mxCap[cost]) {
                mxCap[cost] = cap;
            }
        }
        int[] preSum = new int[budget];
        for (int i = 1; i < budget; i++) {
            int rem = Math.min(budget - i - 1, i - 1);
            maxCap = Math.max(maxCap, mxCap[i] + preSum[rem]);
            preSum[i] = Math.max(preSum[i - 1], mxCap[i]);
        }
        return maxCap;
    }
}