Triple Challenge: Price Drops, Bounded Windows, Twin Rows
Arrays & HashingAuto-graded · 17 test casesLast updated
Combine a threshold binary search with greedy arithmetic sums, a linear scan counting subarrays with exact min and max, and hashing of binary rows to count identical pairs.
Write one function that answers three independent questions and returns the three answers together as a list [revenue, window_count, twin_pairs].
Part 1: Selling with falling prices
stock is a list where stock[i] is the current unit price of product i. Every time you sell one unit of product i, you earn its current price, and the price of that product then drops by 1 (it never goes below 0). Different products are independent.
You must make exactly sales sales in total, choosing which product to sell each time. Maximize the total earnings and return them modulo 1,000,000,007.
If the products can't supply sales sales at positive prices, the remaining sales each earn 0.
Part 2: Subarrays with exact extremes
values is an integer list, and low <= high. Count the contiguous, non-empty subarrays whose smallest element is exactly low and whose largest element is exactly high. If low == high, the subarray must consist entirely of copies of that value.
Part 3: Identical rows after global column flips
grid is a binary matrix. A column flip toggles that column's bit in every row at once, so it never changes whether two rows are equal. Two rows are therefore equivalent exactly when they are identical.
Count the unordered pairs of rows (i, j) with i < j whose contents are identical.
Return value
A list of three integers [revenue, window_count, twin_pairs]:
revenue: the Part 1 answer modulo 1,000,000,007.window_count: the exact Part 2 count (not reduced by a modulus).twin_pairs: the exact Part 3 count.
Constraints
1 <= len(stock) <= 2 * 10^5,1 <= stock[i] <= 10^91 <= sales <= 10^131 <= len(values) <= 2 * 10^5,-10^9 <= values[i] <= 10^9,low <= high1 <= len(grid) <= 10^5, each row has the same lengthmwith1 <= m <= 30, and every entry is 0 or 1- Target complexity: roughly
O(n log max(stock))for Part 1,O(n)for Part 2, andO(n * m)for Part 3.
Examples
Example 1
Input: solve_combined_queries([2, 5], 4, [1, 3, 5, 2, 7], 1, 5, [[1, 0, 1], [0, 1, 0], [1, 0, 1]])
Output: [14, 2, 1]
Example 2
Input: solve_combined_queries([3, 3, 3], 5, [1, 1, 1], 1, 1, [[0, 0], [0, 0], [1, 1]])
Output: [13, 6, 1]
Example 3
Input: solve_combined_queries([10], 3, [-2, -1, 0, 1, 2], -1, 1, [[1], [0], [1], [1]])
Output: [27, 1, 3]
Hints
Hint 1
Part 1: always selling the most expensive unit is optimal. Since sales can be 10^13, don't simulate. Binary search a cutoff price so that everything priced above it is sold and the rest are sold at exactly the cutoff.
Hint 2
Part 1: for a cutoff p, the number of units priced at least p is the sum of max(0, x - p + 1). Use the arithmetic series formula for the earnings of each product, and take the modulus only at the end (Python integers don't overflow).
Hint 3
Part 2: scan left to right, tracking the last index of an out-of-range value and the last indices of low and high. For each right end, the valid starts are those after the bad index and at or before the smaller of the two last indices.
Hint 4
Part 3: turn each row into an integer bitmask and count how many earlier rows have the same mask using a dictionary, adding that count to the answer each time.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Selling with falling prices
Approach. Selling the currently most expensive unit each time is optimal, because any sale at a lower price could be swapped for a higher-priced unit that is still available. Simulating this is too slow for up to 10^13 sales, so we find a cutoff price p instead.
Define count_at_least(p) as the sum of v - p + 1 over all products with v >= p. This is the number of units priced at least p, and it is non-increasing in p. Binary search the largest p for which count_at_least(p) >= sales. Then:
- Every unit priced strictly above
pis sold. A product with pricevcontributesv - punits worth(v + p + 1) * (v - p) / 2. - The remaining sales,
sales - sold_above, are all made at pricep. Becausecount_at_least(p + 1) < sales, there are enough units at pricepto cover them. - If the total stock is smaller than
sales, the cutoff becomes 0 and the extra sales earn nothing.
The modulus is applied once at the end.
Part 2: Subarrays with exact extremes
Approach. Scan once and keep three indices: the last position of a value outside [low, high], the last position of low, and the last position of high.
A subarray [s, i] is valid exactly when it has no out-of-range element (s > last_bad), contains low (s <= last_low), and contains high (s <= last_high). The valid starts therefore form the range (last_bad, min(last_low, last_high)]. Add its length, if positive, for each i. Each subarray is counted once, at its right end. The case low == high works because both indices update together.
Part 3: Identical rows
Approach. A global column flip changes two rows in the same way, so two rows are equivalent exactly when they are identical. Encode each row as an integer bitmask (at most 30 bits). Keep a dictionary of how many times each mask has been seen, and add the earlier count to the answer for every new row. This counts each unordered pair once.
Complexity
- Part 1: O(n log max(stock)) time, O(1) extra space.
- Part 2: O(n) time, O(1) extra space.
- Part 3: O(n·m) time, O(n) space.
Reference solution
from typing import List
MOD = 1_000_000_007
def solve_combined_queries(stock: List[int], sales: int, values: List[int], low: int, high: int, grid: List[List[int]]) -> List[int]:
# Part 1: find the largest cutoff price p such that at least `sales`
# units are priced >= p. Everything above p is sold, the rest at p.
highest = max(stock)
def count_at_least(price):
total = 0
for v in stock:
if v >= price:
total += v - price + 1
return total
lo, hi = 0, highest + 1
while lo + 1 < hi:
mid = (lo + hi) // 2
if count_at_least(mid) >= sales:
lo = mid
else:
hi = mid
cutoff = lo
sold_above = 0
revenue = 0
for v in stock:
if v > cutoff:
cnt = v - cutoff
sold_above += cnt
revenue += cnt * (v + cutoff + 1) // 2
revenue += (sales - sold_above) * cutoff
revenue %= MOD
# Part 2: track last out-of-range index, last low, last high.
last_bad = last_low = last_high = -1
window_count = 0
for i, v in enumerate(values):
if v < low or v > high:
last_bad = i
if v == low:
last_low = i
if v == high:
last_high = i
earliest = min(last_low, last_high)
if earliest > last_bad:
window_count += earliest - last_bad
# Part 3: count identical rows via bitmask frequencies.
freq = {}
twin_pairs = 0
for row in grid:
mask = 0
for bit in row:
mask = (mask << 1) | bit
prev = freq.get(mask, 0)
twin_pairs += prev
freq[mask] = prev + 1
return [revenue, window_count, twin_pairs]