DEV Community

Nithya Dharshini official
Nithya Dharshini official

Posted on

Sliding Window in Action — Solving “Grumpy Bookstore Owner” Step by Step

Sliding Window makes sense only when you see it working in a real problem.
This problem is a great example of how to separate logic and avoid recalculation.

Problem Idea

We are given:

c[i] → number of customers at minute i
g[i] → owner’s mood
Enter fullscreen mode Exit fullscreen mode

0 → not grumpy (customers already happy)
1 → grumpy (customers unhappy)

The owner can use a secret technique for minutes time to make grumpy customers happy.

Goal:

Maximize the total number of happy customers.

Key Observation

Split the solution into two independent parts:

1) Base Happiness

Customers who are already happy (g[i] == 0)
→ These are always counted.

2) Extra Happiness (Sliding Window)

Customers who are grumpy (g[i] == 1)
→ We use a sliding window to choose the best time interval.

Final Answer:

Base + Maximum Window Gain

C++ Implementation

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> c = {1,0,1,2,1,1,7,5};
    vector<int> g = {0,1,0,1,0,1,0,1};

    int windowSize = 3;
    int base = 0, winSum = 0, maxSum = 0;

    // Step 1: Calculate base happiness
    for (int i = 0; i < g.size(); ++i) {
        if (g[i] == 0)
            base += c[i];
    }

    // Step 2: First window
    for (int i = 0; i < windowSize; ++i) {
        if (g[i] == 1)
            winSum += c[i];
    }

    maxSum = winSum;

    // Step 3: Slide the window
    for (int i = windowSize; i < g.size(); ++i) {
        if (g[i - windowSize] == 1)
            winSum -= c[i - windowSize];

        if (g[i] == 1)
            winSum += c[i];

        maxSum = max(maxSum, winSum);
    }

    cout << base + maxSum;
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Sliding Window Logic (Plain English)

  • Calculate the first window
  • Slide right by one step
  • Remove the left element
  • Add the new right element
  • Update the maximum extra gain
  • Only grumpy minutes are handled inside the window.

Complexity

Time O(N)
Space O(1)

Efficient and interview-ready.

What This Problem Teaches

Sliding window avoids full recalculation. Not all elements are equal — filter first. Fixed-size windows are predictable and clean logic becomes simple when you separate concerns

Final Thought

Sliding window isn’t about moving pointers randomly. It’s about controlling change:

  1. what leaves
  2. what enters
  3. what stays constant

Is there any other method to solve the Grumpy Bookstore Owner problem apart from this approach? Please leave it in the comments. 👇

Top comments (0)