DEV Community

Nithya Dharshini official
Nithya Dharshini official

Posted on

Battery Optimization Mode – A Custom Sliding Window Problem(Real World Example)

Problem

Smart glasses run heavy processing tasks like real-time navigation or object detection.Each minute the processor consumes some power.

We are given:

An array power_drain each value represents power consumption per minute (mW).A power_budget which is the maximum safe power usage. Our goal:

-> Find the maximum number of consecutive minutes the glasses can run without exceeding the power budget.

Example

Input

power_drain = [3, 1, 2, 7, 4, 2, 1, 1, 5]
power_budget = 8

Output

4

Explanation

The longest valid subarray is:

[4, 2, 1, 1]

Sum = 8
Length = 4 minutes

Approach — Variable Sliding Window

We use two pointers:

left → start of window
right → end of window

Steps:

  • Expand the window by moving right
  • Add the current power consumption
  • If the total exceeds the budget, shrink from left
  • Track the maximum window length
  • This technique avoids recalculating sums repeatedly.

C++ Implementation

#include <iostream>
#include <vector>

using namespace std;

int main() {

    vector<int> power_drain = {10, 5, 2, 1, 4};
    vector<int> st;

    int power_budget = 4;
    int result = 0;

    int left = 0;
    int minSum = 0;

    for(int right = 0; right < power_drain.size(); right++) {

        st.push_back(power_drain[right]);
        minSum += power_drain[right];

        while(minSum > power_budget) {
            st.erase(st.begin());
            minSum -= power_drain[left];
            left++;
        }

        result = max(result, (int)st.size());
    }

    cout << result;

    return 0;
}

Enter fullscreen mode Exit fullscreen mode

Complexity

Time Complexity - O(n)
Each element enters and leaves the window at most once.

Space Complexity - O(n)
Because we store the current window.

Key Idea

This is called a Variable Sliding Window because the window expands and shrinks depending on the condition.

Condition here:

window_sum <= power_budget

If it exceeds the budget → shrink from the left.

What This Problem Teaches

  1. Real world usage of Sliding Window
  2. Efficient way to find longest subarray with sum ≤ k
  3. Using two pointers technique

This pattern is very common in problems related to:

battery usage
network bandwidth
memory allocation
CPU utilization

Top comments (0)