Library Late Fee Calculator Problem
#3687
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3687.
You are given an integer array daysLate where daysLate[i] indicates how many days late the i^th book was returned.
The penalty is calculated as follows:
- If
daysLate[i] == 1, penalty is 1. - If
2 <= daysLate[i] <= 5, penalty is2 * daysLate[i]. - If
daysLate[i] > 5, penalty is3 * daysLate[i].
Return the total penalty for all books.
Example 1:
Input: daysLate = [5,1,7]
Output: 32
Explanation:
- daysLate[0] = 5: Penalty is 2 * daysLate[0] = 2 * 5 = 10.
- daysLate[1] = 1: Penalty is 1.
- daysLate[2] = 7: Penalty is 3 * daysLate[2] = 3 * 7 = 21.
- Thus, the total penalty is 10 + 1 + 21 = 32.
Example 2:
Input: daysLate = [1,1]
Output: 2
Explanation:
- daysLate[0] = 1: Penalty is 1.
- daysLate[1] = 1: Penalty is 1.
- Thus, the total penalty is 1 + 1 = 2.
Constraints:
1 <= daysLate.length <= 1001 <= daysLate[i] <= 100
Solution
Approach: Simulation
Compute the fee of each book with the rules from the statement: 1 for one day late, 2 * d for 2 to 5 days, and 3 * d for more than 5 days. Then add up the fees.
Complexity: O(n) time and O(1) extra space, where n is the length of daysLate.
class Solution:
def lateFee(self, daysLate: List[int]) -> int:
def f(x: int) -> int:
if x == 1:
return 1
if x > 5:
return 3 * x
return 2 * x
return sum(f(x) for x in daysLate)