Skip to content

3947. Maximum Number of Items From Sale II

SourceWeekly Contest 504 Q3DifficultyMediumRating2215

Description

You are given a 2D integer array items, where items[i] = [factori, pricei] represents the ith item. You are also given an integer budget.

There are unlimited copies of each item available for purchase. You may buy any number of copies of any items such that the total cost of the purchased copies is at most budget.

After buying items, you may receive free copies according to the following rules:

  • Each purchased copy of item i can give you at most one free copy of another item j.
  • The free item must satisfy i != j and factori divides factorj.
  • For each ordered pair (i, j), you can receive a free copy of item j from purchases of item i at most once, regardless of how many copies of item i you buy.
  • The same item j can be received multiple times for free if it is received from purchases of different item types.

Return the maximum total number of item copies you can obtain, including both purchased copies and free copies, while spending at most budget on purchased items.

 

Example 1:

Input: items = [[1,6],[2,4],[3,5]], budget = 19

Output: 5

Explanation:

  • You can buy 2 copies of item 0 and 1 copy of item 1 for a total cost of 2 * 6 + 4 = 16, which is not greater than budget = 19.
  • One purchased copy of item 0 gives 1 free copy of item 1, because factor0 = 1 divides factor1 = 2.
  • The other purchased copy of item 0 gives 1 free copy of item 2, because factor0 = 1 divides factor2 = 3.
  • You leave with 3 purchased copies and 2 free copies, for a total of 5 item copies.

Example 2:

Input: items = [[2,8],[1,10],[6,6],[4,12],[5,20],[5,17]], budget = 35

Output: 7

Explanation:

  • You can buy 2 copies of item 0, 1 copy of item 1, and 1 copy of item 2 for a total cost of 2 * 8 + 10 + 6 = 32, which is not greater than budget = 35.
  • One purchased copy of item 0 gives 1 free copy of item 2, because factor0 = 2 divides factor2 = 6.
  • The other purchased copy of item 0 gives 1 free copy of item 3, because factor0 = 2 divides factor3 = 4.
  • The purchased copy of item 1 gives 1 free copy of item 2, because factor1 = 1 divides factor2 = 6.
  • Buying item 2 gives no free copy, because factor2 = 6 does not divide the factor of any other item.
  • You leave with 4 purchased copies and 3 free copies, for a total of 7 item copies.

 

Constraints:

  • 1 <= items.length <= 105
  • items[i] = [factori, pricei]
  • 1 <= factori <= items.length
  • 1 <= pricei <= 109
  • 1 <= budget <= 109

Solutions

Solution 1: Greedy

Thinking

\(n\) reaches \(10^5\) and the budget reaches \(10^9\), so a knapsack over the budget does not fit.

Buying one item can unlock at most one other item whose factor it divides, and each ordered pair can be used only once. The number of gifts one item can trigger is therefore the number of item types whose factor is a multiple of its factor, minus one.

One purchase plus one gift yields two items, and that is worthwhile only when the price is strictly less than the cost of two cheapest items. Cheaper pairs are better, so the candidates are taken in increasing price order.

Count every factor's gift quota by enumerating multiples, then sort by price. If the current quota cannot be filled, the remaining budget cannot pay for an equally expensive or costlier pair, so the scan stops and the rest of the budget buys the cheapest item.

Buying an item whose factor is \(f\) can earn one free item: the two items are different types, \(f\) divides the other factor, and each ordered pair is used at most once. Let \(\textit{freq}[f]\) be the number of item types whose factor equals \(f\), and let \(\textit{divCount}[f]\) be the number whose factor is a multiple of \(f\). An item of factor \(f\) yields at most \(\textit{divCount}[f]-1\) gifts. \(\textit{divCount}\) is filled by enumerating multiples.

Let \(p_{\min}\) be the lowest price. Paying \(p\) for one item and receiving one gift produces two items. Buying two copies of the cheapest item costs \(2p_{\min}\). Only items with \(p<2p_{\min}\) and a positive gift quota are useful, and they are bought in increasing order of \(p\). If the current quota is \(g\), buy \(t=\min(g,\lfloor\textit{budget}/p\rfloor)\) copies, add \(2t\) to the answer, and subtract \(tp\) from the budget. When \(t<g\), the remaining budget is less than \(p\). Later items are no cheaper, so the scan stops. The leftover budget is spent on items of price \(p_{\min}\).

The time complexity is \(O(n\log n)\), and the space complexity is \(O(n)\), where \(n\) is the number of item types.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution:
    def maximumSaleItems(self, items: list[list[int]], budget: int) -> int:
        n = len(items)
        freq = [0] * (n + 1)
        min_price = float('inf')

        for factor, price in items:
            freq[factor] += 1
            if price < min_price:
                min_price = price

        div_count = [0] * (n + 1)
        for f in range(1, n + 1):
            if freq[f]:
                for m in range(f, n + 1, f):
                    div_count[f] += freq[m]

        sorted_items = sorted((price, div_count[factor] - 1) for factor, price in items)

        ans = 0
        rem = budget
        limit = 2 * min_price

        for price, gain in sorted_items:
            if price >= limit:
                break
            if gain <= 0:
                continue

            can_buy = min(gain, rem // price)
            ans += can_buy * 2
            rem -= can_buy * price

            if can_buy < gain:
                break

        ans += rem // min_price
        return ans
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Solution {
    public int maximumSaleItems(int[][] items, int budget) {
        int n = items.length;
        int[] freq = new int[n + 1];
        int minPrice = Integer.MAX_VALUE;

        for (int[] item : items) {
            freq[item[0]]++;
            minPrice = Math.min(minPrice, item[1]);
        }

        int[] divCount = new int[n + 1];
        for (int f = 1; f <= n; f++) {
            if (freq[f] == 0) continue;
            for (int m = f; m <= n; m += f) {
                divCount[f] += freq[m];
            }
        }

        int[][] sortedItems = new int[n][2];
        for (int i = 0; i < n; i++) {
            sortedItems[i][0] = items[i][1];
            sortedItems[i][1] = divCount[items[i][0]] - 1;
        }

        Arrays.sort(sortedItems, Comparator.comparingInt(a -> a[0]));

        long rem = budget;
        long ans = 0;
        long limit = 2L * minPrice;

        for (int[] item : sortedItems) {
            int price = item[0];
            int gain = item[1];
            if (price >= limit) break;
            if (gain <= 0) continue;

            long canBuy = Math.min((long) gain, rem / price);
            ans += canBuy * 2;
            rem -= canBuy * price;

            if (canBuy < gain) break;
        }

        ans += rem / minPrice;
        return (int) ans;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class Solution {
public:
    long long maximumSaleItems(vector<vector<int>>& items, int budget) {
        int n = items.size();
        vector<int> freq(n + 1, 0);
        int min_price = 2e9;

        for (const auto& item : items) {
            freq[item[0]]++;
            min_price = min(min_price, item[1]);
        }

        vector<int> div_count(n + 1, 0);
        for (int f = 1; f <= n; ++f) {
            if (freq[f] == 0) continue;
            for (int m = f; m <= n; m += f) {
                div_count[f] += freq[m];
            }
        }

        vector<pair<int, int>> sorted_items;
        sorted_items.reserve(n);
        for (const auto& item : items) {
            sorted_items.push_back({item[1], div_count[item[0]] - 1});
        }
        sort(sorted_items.begin(), sorted_items.end());

        long long rem = budget;
        long long ans = 0;

        for (const auto& [price, gain] : sorted_items) {
            if (price >= 2LL * min_price) break;
            if (gain <= 0) continue;

            long long can_buy = min((long long) gain, rem / price);
            ans += can_buy * 2;
            rem -= can_buy * price;

            if (can_buy < gain) break;
        }

        ans += rem / min_price;
        return ans;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
func maximumSaleItems(items [][]int, budget int) int {
    n := len(items)
    freq := make([]int, n+1)
    minPrice := int(2e9)

    for _, item := range items {
        freq[item[0]]++
        if item[1] < minPrice {
            minPrice = item[1]
        }
    }

    divCount := make([]int, n+1)
    for f := 1; f <= n; f++ {
        if freq[f] == 0 {
            continue
        }
        for m := f; m <= n; m += f {
            divCount[f] += freq[m]
        }
    }

    type pair struct {
        price int
        gain  int
    }
    sortedItems := make([]pair, n)
    for i, item := range items {
        sortedItems[i] = pair{price: item[1], gain: divCount[item[0]] - 1}
    }

    sort.Slice(sortedItems, func(i, j int) bool {
        return sortedItems[i].price < sortedItems[j].price
    })

    rem := int64(budget)
    var ans int64 = 0
    limit := int64(2) * int64(minPrice)

    for _, item := range sortedItems {
        if int64(item.price) >= limit {
            break
        }
        if item.gain <= 0 {
            continue
        }

        canBuy := rem / int64(item.price)
        if int64(item.gain) < canBuy {
            canBuy = int64(item.gain)
        }

        ans += canBuy * 2
        rem -= canBuy * int64(item.price)

        if canBuy < int64(item.gain) {
            break
        }
    }

    ans += rem / int64(minPrice)
    return int(ans)
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
function maximumSaleItems(items: number[][], budget: number): number {
    const n = items.length;
    const freq = new Array<number>(n + 1).fill(0);
    let minPrice = Infinity;

    for (const item of items) {
        freq[item[0]]++;
        if (item[1] < minPrice) {
            minPrice = item[1];
        }
    }

    const divCount = new Array<number>(n + 1).fill(0);
    for (let f = 1; f <= n; f++) {
        if (freq[f] === 0) {
            continue;
        }
        for (let m = f; m <= n; m += f) {
            divCount[f] += freq[m];
        }
    }

    const sortedItems = items.map(item => [item[1], divCount[item[0]] - 1]);
    sortedItems.sort((a, b) => a[0] - b[0]);

    let rem = budget;
    let ans = 0;
    const limit = 2 * minPrice;

    for (const [price, gain] of sortedItems) {
        if (price >= limit) {
            break;
        }
        if (gain <= 0) {
            continue;
        }

        const canBuy = Math.min(gain, Math.floor(rem / price));
        ans += canBuy * 2;
        rem -= canBuy * price;

        if (canBuy < gain) {
            break;
        }
    }

    ans += Math.floor(rem / minPrice);
    return ans;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
impl Solution {
    pub fn maximum_sale_items(items: Vec<Vec<i32>>, budget: i32) -> i32 {
        let n = items.len();
        let mut freq = vec![0i64; n + 1];
        let mut min_price = i64::MAX;
        for item in &items {
            let factor = item[0] as usize;
            let price = item[1] as i64;
            freq[factor] += 1;
            min_price = min_price.min(price);
        }

        let mut div_count = vec![0i64; n + 1];
        for f in 1..=n {
            if freq[f] == 0 {
                continue;
            }
            for m in (f..=n).step_by(f) {
                div_count[f] += freq[m];
            }
        }

        let mut sorted_items: Vec<(i64, i64)> = items
            .iter()
            .map(|item| (item[1] as i64, div_count[item[0] as usize] - 1))
            .collect();
        sorted_items.sort_unstable();

        let mut ans = 0i64;
        let mut rem = budget as i64;
        let limit = 2 * min_price;
        for (price, gain) in sorted_items {
            if price >= limit {
                break;
            }
            if gain <= 0 {
                continue;
            }
            let can_buy = gain.min(rem / price);
            ans += can_buy * 2;
            rem -= can_buy * price;
            if can_buy < gain {
                break;
            }
        }
        ans += rem / min_price;
        ans as i32
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
var maximumSaleItems = function (items, budget) {
    const n = items.length;
    const freq = new Int32Array(n + 1);
    let minPrice = Infinity;

    for (let i = 0; i < n; i++) {
        freq[items[i][0]]++;
        if (items[i][1] < minPrice) minPrice = items[i][1];
    }

    const divCount = new Int32Array(n + 1);
    for (let f = 1; f <= n; f++) {
        if (freq[f] === 0) continue;
        for (let m = f; m <= n; m += f) {
            divCount[f] += freq[m];
        }
    }

    const sortedItems = items.map(([factor, price]) => [price, divCount[factor] - 1]);
    sortedItems.sort((a, b) => a[0] - b[0]);

    let rem = budget;
    let ans = 0;
    const limit = 2 * minPrice;

    for (let i = 0; i < n; i++) {
        const [price, gain] = sortedItems[i];
        if (price >= limit) break;
        if (gain <= 0) continue;

        const canBuy = Math.min(gain, Math.floor(rem / price));
        ans += canBuy * 2;
        rem -= canBuy * price;

        if (canBuy < gain) break;
    }

    ans += Math.floor(rem / minPrice);
    return ans;
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
public class Solution {
    public int MaximumSaleItems(int[][] items, int budget) {
        int n = items.Length;
        int[] freq = new int[n + 1];
        int minPrice = int.MaxValue;

        foreach (var item in items) {
            freq[item[0]]++;
            if (item[1] < minPrice) {
                minPrice = item[1];
            }
        }

        int[] divCount = new int[n + 1];
        for (int f = 1; f <= n; f++) {
            if (freq[f] == 0) {
                continue;
            }
            for (int m = f; m <= n; m += f) {
                divCount[f] += freq[m];
            }
        }

        var sortedItems = new (int price, int gain)[n];
        for (int i = 0; i < n; i++) {
            sortedItems[i] = (items[i][1], divCount[items[i][0]] - 1);
        }

        Array.Sort(sortedItems, (a, b) => a.price.CompareTo(b.price));

        long rem = budget;
        long ans = 0;
        long limit = 2L * minPrice;

        foreach (var (price, gain) in sortedItems) {
            if (price >= limit) {
                break;
            }
            if (gain <= 0) {
                continue;
            }

            long canBuy = Math.Min((long)gain, rem / price);
            ans += canBuy * 2;
            rem -= canBuy * price;

            if (canBuy < gain) {
                break;
            }
        }

        ans += rem / minPrice;
        return (int)ans;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
class Solution {
    function maximumSaleItems($items, $budget) {
        $n = count($items);
        $freq = array_fill(0, $n + 1, 0);
        $minPrice = PHP_INT_MAX;

        foreach ($items as $item) {
            $freq[$item[0]]++;
            if ($item[1] < $minPrice) {
                $minPrice = $item[1];
            }
        }

        $divCount = array_fill(0, $n + 1, 0);
        for ($f = 1; $f <= $n; $f++) {
            if ($freq[$f] === 0) {
                continue;
            }
            for ($m = $f; $m <= $n; $m += $f) {
                $divCount[$f] += $freq[$m];
            }
        }

        $sortedItems = [];
        foreach ($items as $item) {
            $sortedItems[] = [$item[1], $divCount[$item[0]] - 1];
        }

        usort($sortedItems, fn($a, $b) => $a[0] <=> $b[0]);

        $rem = $budget;
        $ans = 0;
        $limit = 2 * $minPrice;

        foreach ($sortedItems as [$price, $gain]) {
            if ($price >= $limit) {
                break;
            }
            if ($gain <= 0) {
                continue;
            }

            $canBuy = min($gain, intdiv($rem, $price));
            $ans += $canBuy * 2;
            $rem -= $canBuy * $price;

            if ($canBuy < $gain) {
                break;
            }
        }

        $ans += intdiv($rem, $minPrice);
        return $ans;
    }
}

Comments