LeetCode 1809: Ad-Free Sessions
Problem Description
Explanation:
To solve this problem, we need to iterate through the given list of session lengths and count the number of ad-free sessions that can be played based on the given ad duration. We can achieve this by keeping track of the total time taken by the sessions and incrementing the count of ad-free sessions whenever the total time exceeds the ad duration.
Algorithm:
- Initialize total time taken as 0 and ad-free sessions count as 0.
- Iterate through the given list of session lengths.
- For each session length:
- Add the current session length to the total time taken.
- If the total time taken is less than or equal to the ad duration, increment the ad-free sessions count.
- If the total time taken exceeds the ad duration, reset the total time taken to 0.
- Return the ad-free sessions count.
Time Complexity: O(N) where N is the number of session lengths in the input list. Space Complexity: O(1)
:
Solutions
class Solution {
public int adFreeSessions(int[] sessions, int adDuration) {
int totalSessions = sessions.length;
int totalTime = 0;
int adFreeSessionsCount = 0;
for (int i = 0; i < totalSessions; i++) {
totalTime += sessions[i];
if (totalTime <= adDuration) {
adFreeSessionsCount++;
} else {
totalTime = 0;
}
}
return adFreeSessionsCount;
}
}
Loading editor...