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 After Test Operations INPUT batteryPercentages array: 1 i=0 1 i=1 2 i=2 1 i=3 3 i=4 5 Devices to Test: 1% 1% 2% 1% 3% Input Array: [1, 1, 2, 1, 3] ALGORITHM STEPS 1 Initialize Variables testedCount = 0, drain = 0 2 For Each Device i Calc effective = battery[i] - drain 3 If effective greater than 0 testedCount++, drain++ 4 Return testedCount Total devices tested Execution Trace: i bat drain eff tested 0 1 0 1 1 1 1 1 0 1 2 2 1 1 2 3 1 2 -1 2 4 3 2 1 3 FINAL RESULT Devices Tested: OK i=0 SKIP i=1 OK i=2 SKIP i=3 OK i=4 = Tested = Skipped Devices 0, 2, 4 were tested Devices 1, 3 were skipped OUTPUT 3 Key Insight: Cumulative Drain Optimization Instead of modifying all remaining batteries after each test (O(n^2)), track cumulative drain. Effective battery = original - drain. If effective greater than 0, test device and increment drain. This achieves O(n) time complexity with O(1) space - no actual array modification needed! TutorialsPoint - Count Tested Devices After Test Operations | Cumulative Drain Optimization
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