Data Structures & AlgorithmsVery hardProduct company OA
Sum over all subarrays of (max − min), computed as Σ max − Σ min with two monotonic-stack passes, checked against brute force. What is printed?
Sum over all subarrays of (max − min), computed as Σ max − Σ min with two monotonic-stack passes, checked against brute force. What is printed?
def spread(a):
n = len(a); total = 0
for sign in (1, -1):
b = [sign * x for x in a]; st = []; left = [0] * n
for i in range(n):
while st and b[st[-1]] < b[i]: st.pop()
left[i] = i - (st[-1] if st else -1); st.append(i)
st = []; right = [0] * n
for i in range(n - 1, -1, -1):
while st and b[st[-1]] <= b[i]: st.pop()
right[i] = (st[-1] if st else n) - i; st.append(i)
total += sum(b[i] * left[i] * right[i] for i in range(n))
return total
a = [4, 1, 3, 2]
print(spread(a), sum(max(a[i:j]) - min(a[i:j]) for i in range(4) for j in range(i + 1, 5)))- A. 14 14
- B. 14 12
- C. 12 12
- D. 17 14
Correct answer: A. 14 14
Negating the array turns 'contribution as minimum' into 'contribution as maximum', so one routine computes both: Σ max = 4+4+4+4+1+3+3+3+3+2 = 31, Σ min = 4+1+1+1+1+1+1+3+2+2 = 17, difference 14 – the same as the brute force. The ≤ vs < tie-breaking on the two sides is what keeps equal values from being counted twice. O(n) instead of O(n²).
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- Merging files costs the size of the result each time. Compare the greedy 'always merge the two smallest' (heap) with merging left to right…
- You must count pairs i < j with a[i] + a[j] ≤ T for n ≤ 2·10⁵ values up to 10⁹ in absolute value (time limit 1 s). Which plan passes?
- A service stores n = 10⁵ integer keys in a chained hash table with m = 1000 buckets and h(k) = k mod m. An attacker sends keys that are…
- An empty queue performs: enqueue 7, enqueue 2, enqueue 9, dequeue, enqueue 4, dequeue. Which element is now at the front?
- In a doubly linked list you are given a pointer to a node X somewhere in the middle. What is the time to delete X?
- A hash table has 7 slots and uses h(k) = k mod 7. In which slot is the key 50 placed if that slot is empty?