计算力扣银行的钱
难度:
标签:
题目描述
代码结果
运行时间: 20 ms, 内存: 15.9 MB
/*
* Solution in Java using Streams
* The problem requires calculating the total amount saved in the bank after n days.
* The amount saved follows a pattern where each day of the week the saving increases by 1 starting from 1 on Monday.
* Each subsequent Monday the starting amount increases by 1.
* For example, if n = 10, the savings would be 1, 2, 3, 4, 5, 6, 7, 2, 3, 4.
*/
import java.util.stream.IntStream;
public class SavingsCalculatorStream {
public int totalSavings(int n) {
return IntStream.rangeClosed(1, n)
.map(i -> ((i - 1) / 7) + 1 + ((i - 1) % 7))
.sum();
}
public static void main(String[] args) {
SavingsCalculatorStream scs = new SavingsCalculatorStream();
System.out.println(scs.totalSavings(4)); // Output: 10
System.out.println(scs.totalSavings(10)); // Output: 37
System.out.println(scs.totalSavings(20)); // Output: 96
}
}
解释
方法:
题解首先通过整除和取余操作将天数分解为完整的周数和剩余的天数。对于每一完整的周,采用循环来计算每周存款的总额,每周的存款起始金额比上一周多1块钱。计算完所有完整的周之后,再计算剩余天数的存款总额。通过累加每周的存款和剩余天数的存款得到最终的总金额。
时间复杂度:
O(n)
空间复杂度:
O(1)
代码细节讲解
🦆
在算法中,为什么选择使用循环来处理每周的存款,是否有其他更高效的数学公式可以直接计算出每周的总存款?
▷🦆
在计算剩余天数存款时,你是如何确定`base`变量的值的?请解释这个值是如何计算得出的。
▷🦆
代码中使用了`range(base, base + 7)`和`range(base, base + days)`,请问这种使用范围函数的方式是否考虑了所有边界情况?例如,当剩余天数为0时,这段代码的行为是什么?
▷🦆
在整个解决方案中,是否考虑了`n`为非常小(例如n=1)或非常大(例如n=10000)的情况?这会对算法的效率产生什么影响?
▷