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

October 6, 2025 · View on GitHub

English Version

题目描述

给定一个整数数组 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

解法

方法一:模拟

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

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

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

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

Python3

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)

Java

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;
    }
}

C++

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;
    }
};

Go

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
}

TypeScript

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);
}