Practice Discrete Math

Algorithms / Monotonic Deque Prefix Sum

Least You Need to Know: Monotonic Deques, Prefix Sums, and Shortest Valid Windows

Some subarray problems use prefix sums plus a monotonic deque over prefix indices. The deque keeps promising earlier prefixes in increasing order so the current prefix can quickly detect the shortest earlier start that already makes the sum large enough.

جو کم از کم جاننا ضروری ہے

اہم علامتیں

P[i] prefix sum of the first i elements
P[j] - P[i] sum of the subarray from i to j-1
dominated prefix an earlier prefix with a larger sum than a later candidate

مختصر حل شدہ مثال

  • Build prefix sums `P[0], P[1], ..., P[n]`.
  • Maintain deque indices whose prefix sums are increasing.
  • At each new prefix `P[j]`, pop from the front while `P[j] - P[front]` already meets the target, recording shorter lengths.
  • Pop from the back while `P[j]` is smaller than the back prefix, because the back is dominated.

عام غلطیاں

اس قسم کے سوال کو کیسے پہچانیں

Next recommended lesson

Continue through this topic with Least You Need to Know: Monotonic Queues and Sliding-Window Extremes.

Least You Need to Know: Monotonic Queues and Sliding-Window Extremes

Related lessons

Keep going with nearby lessons in the same topic.

More ways to explore

مشق شروع کریں