Three Independent Array Challenges
Arrays & HashingAuto-graded · 15 test casesLast updated
Tests greedy gain selection, modular triplet counting, and DP-based longest flexible non-decreasing subarray in one combined function.
You are given seven inputs describing three completely independent subproblems. Solve all three and return their answers as a list of three integers in order.
Part 1: Best Score with Optional Doublings
You have two integer arrays a and b, each of length n, and an integer k.
At every position i the baseline contribution to the total score is min(a[i], b[i]).
You may pick a set of at most k distinct positions. For each picked position i, replace b[i] with 2 * b[i] for the purpose of that position's contribution only; the contribution at i becomes min(a[i], 2 * b[i]). No position may be picked more than once. You do not have to pick exactly k positions; picking fewer is allowed if it does not reduce the score (which it cannot, since every gain is non-negative).
Return the maximum possible total score.
How to compute it: the gain from picking position i is min(a[i], 2*b[i]) - min(a[i], b[i]), which is always >= 0. Pick the positions with the k largest gains (breaking ties arbitrarily, since any tie-breaking gives the same total). Sum the base contributions and add those gains.
Part 2: Triplets Whose Sum is Divisible by d
You have an integer array nums and a positive integer d.
Count every ordered-by-index triplet of positions (i, j, k) satisfying all of:
0 <= i < j < k < len(nums)(strictly increasing indices, so all three positions are distinct)(nums[i] + nums[j] + nums[k]) % d == 0
Return that count as a non-negative integer. Use Python's % operator (which always returns a value in [0, d) even for negative inputs) or equivalent non-negative modulo when checking divisibility.
Part 3: Longest Flexible Non-Decreasing Contiguous Window
You have two integer arrays A and B, each of length n.
Consider any contiguous index range [l, r] (with 0 <= l <= r < n). For each position i in [l, r] independently choose either A[i] or B[i]. The resulting sequence of chosen values must be non-decreasing (ties are allowed: chosen[i] <= chosen[i+1] for every consecutive pair within the window).
Return the maximum possible length r - l + 1 of any such window. A single-element window always has length 1, so the answer is at least 1 when n >= 1.
Return Value
Return a list [answer1, answer2, answer3] where each element is the integer answer to the corresponding part.
Constraints
1 <= n <= 200 000(applies to both thea/bpair and theA/Bpair independently)0 <= k <= n0 <= a[i], b[i] <= 10^93 <= len(nums) <= 200 0001 <= d <= 200 000-10^9 <= nums[i] <= 10^9-10^9 <= A[i], B[i] <= 10^9- The
a/barrays and theA/Barrays are guaranteed to be non-empty and of equal length. - Intermediate sums in Part 1 can exceed 32-bit integer range; Python handles this natively.
Examples
Example 1
Input: solve_three_array_problems([4, 5, 2], [3, 2, 4], 2, [1, 2, 3, 4], 3, [1, 3, 2], [2, 2, 4])
Output: [10, 2, 3]
Example 2
Input: solve_three_array_problems([1, 10], [5, 2], 1, [0, 0, 0], 1, [-2, 5], [-1, 4])
Output: [5, 1, 2]
Hints
Hint 1
For Part 1, the gain from doubling b[i] at any position is independent of every other choice. Compute gain[i] = min(a[i], 2*b[i]) - min(a[i], b[i]) for each position, then add the k largest values to the base sum. Gains are non-negative, so never skip a pick unless you've already used all k.
Hint 2
For Part 2, work in residues modulo d. Scan left to right; maintain a running dictionary from 'pair residue sum mod d' to the count of such pairs seen before the current index. For each new element with residue r, look up how many prior pairs have pair-sum residue (-r) % d — those all form valid triplets with the current element. Then add new pairs formed between this element and each element seen…
Hint 3
For Part 3, two DP values per step are enough: the length of the longest valid window ending at position i when you pick A[i], and when you pick B[i]. Extend from the previous step only if the previous chosen value is <= the value you are about to choose. The answer is the running maximum of both states.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Part 1 — Greedy gain selection
Doubling b[i] at position i changes that position's contribution from min(a[i], b[i]) to min(a[i], 2*b[i]). Define:
gain[i] = min(a[i], 2*b[i]) - min(a[i], b[i])
Because 2*b[i] >= b[i] (all values are non-negative), every gain is >= 0. Gains are also completely independent: picking index i has no effect on any other index. Therefore the total score equals the base sum plus the gains at chosen positions, and the optimal strategy is to pick the k positions with the largest gains. Any choice of k positions is matched or beaten by swapping in the largest unused gains, so greedy is provably optimal.
- Time: O(n log n) for sorting
- Space: O(n) for the gains list
Key edge cases: k = 0 → return base sum. When a[i] <= b[i] the cap binds at a[i] already, so min(a[i], 2*b[i]) = a[i] and gain is 0.
Part 2 — Residue-pair prefix counting
Only remainders modulo d matter. A brute-force O(n³) triple loop is too slow.
Instead, scan left to right and maintain a dictionary pair_sums mapping each pair-residue-sum (r_i + r_j) % d to how many pairs (i, j) with i < j < current index produce it. When processing the element at index k with residue r:
- Add
pair_sums.get((-r) % d, 0)to the triplet count — these are all prior pairs whose combined residue, when added tor, gives a multiple ofd. - Register every new pair formed between the current element and each previously seen element.
- Append
rtoprior.
This is O(n²) in the worst case (each element pairs with all prior ones), which is correct and matches the number of possible pairs.
Python's % operator returns values in [0, d) even for negative inputs, so no special normalisation is needed.
Edge cases: d = 1 → every triplet qualifies (all residues are 0). Negative nums[i] values are handled correctly by Python's modulo.
Part 3 — Two-state linear DP
At each index i, the only information needed to extend a window is the last chosen value (since non-decreasing is a purely pairwise constraint). The choice is binary, so two states suffice:
end_a: length of the longest valid window ending atiwhenA[i]is chosenend_b: length of the longest valid window ending atiwhenB[i]is chosen
Recurrence for value v ∈ {A[i], B[i]}:
end_v = 1 + max(
end_a if A[i-1] <= v else 0,
end_b if B[i-1] <= v else 0
)
Correctness: any valid window [l, i] ending in value v has a valid prefix [l, i-1] whose last chosen value is <= v, so the recurrence captures it. It never overcounts because extending requires the predecessor value to be <= v. The answer is the running maximum of both states across all positions.
- Time: O(n)
- Space: O(1) (only the two previous states are kept)
Edge cases: n = 1 → initial longest = 1 is returned. Equal adjacent values satisfy <= and extend the window correctly.
Full Reference Solution
from typing import List
def solve_three_array_problems(
a: List[int],
b: List[int],
k: int,
nums: List[int],
d: int,
A: List[int],
B: List[int],
) -> List[int]:
# ------------------------------------------------------------------
# Part 1: greedy top-k gain selection
# ------------------------------------------------------------------
base = sum(min(x, y) for x, y in zip(a, b))
gains = sorted(
(min(x, 2 * y) - min(x, y) for x, y in zip(a, b)),
reverse=True,
)
score = base + sum(g for g in gains[:k] if g > 0)
# ------------------------------------------------------------------
# Part 2: count triplets (i < j < k) with sum divisible by d
# ------------------------------------------------------------------
pair_sums: dict = {}
triplets = 0
prior: list = []
for value in nums:
r = value % d
triplets += pair_sums.get((-r) % d, 0)
for prev_r in prior:
key = (prev_r + r) % d
pair_sums[key] = pair_sums.get(key, 0) + 1
prior.append(r)
# ------------------------------------------------------------------
# Part 3: two-state linear DP
# ------------------------------------------------------------------
end_a = end_b = longest = 1
for i in range(1, len(A)):
pa, pb = A[i - 1], B[i - 1]
next_a = 1 + max(
end_a if pa <= A[i] else 0,
end_b if pb <= A[i] else 0,
)
next_b = 1 + max(
end_a if pa <= B[i] else 0,
end_b if pb <= B[i] else 0,
)
end_a, end_b = next_a, next_b
longest = max(longest, end_a, end_b)
return [score, triplets, longest]