Online store~25 min2s · 256 MBtarget O(n) time, O(k) spaceclassic twin: lc-2461window-counts · sliding-window-fixed · hashing
An online store's catalogue page shows listings in a row. Some products appear in more than one listing, for example when a product also fills a sponsored slot.
The merchandising team builds a bundle offer from k consecutive listings on the page. A bundle must hold k different products, because a customer does not want two of the same item. Among all valid bundles, the team wants the one with the largest total price.
Prices are integers in minor units. If every run of k listings repeats a product, the page gets no bundle offer.
Write best_bundle(products, prices, k).
i shows product products[i] at price prices[i]. The two arrays have the same length n, and 1 ≤ k ≤ n.k consecutive listings whose product ids are all different.prices over all bundles.k consecutive listings has k different products, return -1.Input: products = [3, 5, 3, 8, 6, 8, 1], prices = [40, 25, 30, 50, 20, 45, 35], k = 3
Output: 105| right | Joins (price) | Leaves (price) | Products in the window | Different products | Total | Best |
|---|---|---|---|---|---|---|
| 0 | 3 (40) | none | 3 | 1 | 40 | not full yet |
| 1 | 5 (25) | none | 3, 5 | 2 | 65 | not full yet |
| 2 | 3 (30) | none | 3, 5, 3 | 2 | 95 | -1 |
| 3 | 8 (50) | 3 (40) | 5, 3, 8 | 3 | 105 | 105 |
| 4 | 6 (20) | 5 (25) | 3, 8, 6 | 3 | 100 | 105 |
| 5 | 8 (45) | 3 (30) | 8, 6, 8 | 2 | 115 | 105 |
| 6 | 1 (35) | 8 (50) | 6, 8, 1 | 3 | 100 | 105 |
The window 8, 6, 8 has the largest total, 115, but it repeats product 8, so it is not a bundle.
Input: products = [6, 6, 6], prices = [10, 20, 30], k = 2
Output: -1Every pair of listings shows product 6 twice, so there is no bundle.
Input: products = [2, 9], prices = [15, 70], k = 2
Output: 85The only window is the whole page, and its two products are different.
1 ≤ k ≤ products.length = prices.length ≤ 10^51 ≤ products[i] ≤ 10^61 ≤ prices[i] ≤ 10^7Checking every window from scratch costs (n − k + 1) × k steps. With n = 10^5 and k = 5 × 10^4, that is about 2.5 × 10^9 steps, far over the time limit. Aim for O(n).
Read the values too. A bundle can hold 10^5 listings at up to 10^7 each, a total of 10^12, so the total needs a 64-bit integer in Java and C++.