[LeetCode] Count Tested Devices After Test Operations

10031. Count Tested Devices After Test Operations

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int countTestedDevices(vector<int>& batteryPercentages) {
int res = 0, pre = 0;
for(auto& x : batteryPercentages) {
x -= pre;
if(x > 0) {
res += 1;
pre += 1;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/12/10/PS/LeetCode/count-tested-devices-after-test-operations/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.