Battery relapse log
EasyOnline Assessment
Find out when a phone battery goes from full to flat, using its charge log.
The battery holds at most capacity units of charge and starts at start. Each entry of changes is applied in order: positive values charge, negative values drain. The charge can never go above capacity or below 0; after each change it is clamped to that range (a charge of +40 on a battery at 80 of 100 leaves it at 100, and the extra 20 is lost).
Call a reading full when the charge after a change equals capacity, and flat when it equals 0. The battery also counts as full before the first change if start == capacity.
A relapse is a flat reading that comes after the battery has been full at some earlier point, with no other relapse between them. After a relapse is recorded, the battery has to become full again before another one can count. (So a battery that stays at 0 for several readings records only one relapse, and a flat reading with no full reading before it records none.)
Input: capacity, start, and the list changes.
Output: a list [first, count]. first is the 0-based index in changes of the reading at which the first relapse happened, or -1 if there was none. count is the number of relapses in total.
Example 1
- Input:
- [100,40,[30,40,-20,-85,5,50,50,-200]]
- Output:
- [3,2]
- Explanation
- The battery starts at 40 and is clamped to
[0, 100]: 70, then 40 more would be 110 so it stops at 100 (full). Then 80, then -85 would be -5, so it is clamped to 0 at reading 3, the first time it is empty after being full. It recharges (5, 55, 100 - full again) and is empty again at reading 7. Answer[3, 2].
Example 2
- Input:
- [50,50,[-10,-40,0,20,-30]]
- Output:
- [1,1]
- Explanation
- The battery starts full (50), so being empty counts straight away: reading 1 is 0. Reading 2 stays at 0 and does not count again. It then rises to 20 and falls back to 0, but it was never full again in between, so there is no second cycle. Answer
[1, 1].
Example 3
- Input:
- [10,0,[5,-5,10,-3]]
- Output:
- [-1,0]
- Explanation
- It is empty at reading 1 (after 5, then -5), but it has never been full by then. It is full at reading 2 and never empties afterwards. No cycle is completed:
[-1, 0].
Constraints
1 <= capacity <= 10,0000 <= start <= capacity0 <= changes.length <= 500-20,000 <= changes[i] <= 20,000