跳转至

3687. 图书馆逾期罚款计算器 🔒

题目描述

给定一个整数数组 daysLate,其中 daysLate[i] 表示第 i 书的归还日期晚了几天。

罚款计算如下:

  • 如果 daysLate[i] == 1,罚款为 1。
  • 如果 2 <= daysLate[i] <= 5,罚款为 2 * daysLate[i]
  • 如果 daysLate[i] > 5,罚款为 3 * daysLate[i]

返回所有书的总罚款。

 

示例 1:

输入:daysLate = [5,1,7]

输入:32

解释:

  • daysLate[0] = 5:罚款是 2 * daysLate[0] = 2 * 5 = 10
  • daysLate[1] = 1:罚款是 1
  • daysLate[2] = 7:罚款是 3 * daysLate[2] = 3 * 7 = 21
  • 因此,总罚款为 10 + 1 + 21 = 32

示例 2:

输入:daysLate = [1,1]

输出:2

解释:

  • daysLate[0] = 1:罚款为 1
  • daysLate[1] = 1:罚款为 1
  • 因此,总罚款为 1 + 1 = 2

 

提示:

  • 1 <= daysLate.length <= 100
  • 1 <= daysLate[i] <= 100

解法

方法一:模拟

我们定义一个函数 \(\text{f}(x)\) 来计算每本书的罚款:

\[ \text{f}(x) = \begin{cases} 1 & x = 1 \\ 2x & 2 \leq x \leq 5 \\ 3x & x > 5 \end{cases} \]

然后我们对数组 \(\textit{daysLate}\) 中的每个元素 \(x\) 计算 \(\text{f}(x)\) 并累加得到总罚款。

时间复杂度 \(O(n)\),其中 \(n\) 是数组 \(\textit{daysLate}\) 的长度。空间复杂度 \(O(1)\)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
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)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
    public int lateFee(int[] daysLate) {
        IntUnaryOperator f = x -> {
            if (x == 1) {
                return 1;
            } else if (x > 5) {
                return 3 * x;
            } else {
                return 2 * x;
            }
        };

        int ans = 0;
        for (int x : daysLate) {
            ans += f.applyAsInt(x);
        }
        return ans;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
    int lateFee(vector<int>& daysLate) {
        auto f = [](int x) {
            if (x == 1) {
                return 1;
            } else if (x > 5) {
                return 3 * x;
            } else {
                return 2 * x;
            }
        };

        int ans = 0;
        for (int x : daysLate) {
            ans += f(x);
        }
        return ans;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
func lateFee(daysLate []int) (ans int) {
    f := func(x int) int {
        if x == 1 {
            return 1
        } else if x > 5 {
            return 3 * x
        }
        return 2 * x
    }
    for _, x := range daysLate {
        ans += f(x)
    }
    return
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
function lateFee(daysLate: number[]): number {
    const f = (x: number): number => {
        if (x === 1) {
            return 1;
        } else if (x > 5) {
            return 3 * x;
        }
        return 2 * x;
    };
    return daysLate.reduce((acc, days) => acc + f(days), 0);
}

评论