Count Tested Devices After Test Operations - Problem

You are given a 0-indexed integer array batteryPercentages having length n, denoting the battery percentages of n 0-indexed devices.

Your task is to test each device i in order from 0 to n - 1, by performing the following test operations:

  • If batteryPercentages[i] is greater than 0:
    • Increment the count of tested devices.
    • Decrease the battery percentage of all devices with indices j in the range [i + 1, n - 1] by 1, ensuring their battery percentage never goes below 0, i.e, batteryPercentages[j] = max(0, batteryPercentages[j] - 1).
    • Move to the next device.
  • Otherwise, move to the next device without performing any test.

Return an integer denoting the number of devices that will be tested after performing the test operations in order.

Input & Output

Example 1 — Basic Testing Sequence
$ Input: batteryPercentages = [1,1,2,1,3]
Output: 3
💡 Note: Device 0: battery=1>0, test it (count=1), drain others → [1,0,1,0,2]. Device 1: battery=0, skip. Device 2: battery=1>0, test it (count=2), drain others → [1,0,1,0,1]. Device 3: battery=0, skip. Device 4: battery=1>0, test it (count=3). Total tested = 3.
Example 2 — All Zeros
$ Input: batteryPercentages = [0,0,0]
Output: 0
💡 Note: All devices start with 0 battery, so none can be tested. Return 0.
Example 3 — Single Device
$ Input: batteryPercentages = [5]
Output: 1
💡 Note: Only one device with battery=5>0, test it. No other devices to drain. Return 1.

Constraints

  • 1 ≤ batteryPercentages.length ≤ 100
  • 0 ≤ batteryPercentages[i] ≤ 100

Visualization

Tap to expand
Count Tested Devices: Battery Testing ProcessInput:11213index 0index 1index 2index 3index 4Process:Test each device in order (0→1→2→3→4)If battery > 0: test it, drain all future devices by 1Count successful testsOutput:3devicestestedDevices 0, 2, and 4 had sufficient battery after cumulative drain
Understanding the Visualization
1
Input
Array of battery percentages: [1,1,2,1,3]
2
Process
Test devices in order, each test drains future devices by 1
3
Output
Count of successfully tested devices: 3
Key Takeaway
🎯 Key Insight: Track cumulative drain instead of updating all devices for O(n) efficiency
Asked in
Amazon 15 Microsoft 8
12.0K Views
Medium Frequency
~15 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen