1716. Calculate Money in Leetcode Bank
- 題目描述
- 解答
Description
Hercy wants to save money for his first car. He puts money in the Leetcode bank every day.
He starts by putting in 1 more than the day before. On every subsequent Monday, he will put in $1 more than the previous Monday.
Given n, return the total amount of money he will have in the Leetcode bank at the end of the nth day.
Example 1:
Input: n = 4
Output: 10
Explanation:
After the 4th day, the total is 1 + 2 + 3 + 4 = 10.
Example 2:
Input: n = 10
Output: 37
Explanation:
After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2.
Example 3:
Input: n = 20
Output: 96
Explanation:
After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96.
Constraints:
- 0
<=n<=
Solution
/**
* @param {number} n
* @return {number}
*/
var totalMoney = function (n) {
const totalWeeks = Math.floor(n / 7);
const days = n % 7;
let result = ((28 + (28 + 7 * (totalWeeks - 1))) * totalWeeks) / 2;
result += (days * (days + 1)) / 2 + days * totalWeeks;
return result;
};
解題思路
先算出目前天數等於幾週又幾天
const totalWeeks = Math.floor(n / 7); // 總週數
const days = n % 7; // 其餘天數
再用等差數列公式算出題目要求的結果
等差數列的和 = (首項 + 末項) * 項數 / 2
所以假設有 totalWeeks 週
首項會是 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28
末項會是 28 + 7 * (totalWeeks - 1)
-1 是因為第一週不變是 28
第二週 = 28 + 7 * (2 - 1) = 35
第三週 28 + 7 * (3 - 1) = 42
以此類推
項數就是 totalWeeks
套用公式就會變成 ((28 + (28 + 7 * (totalWeeks - 1))))* totalWeeks / 2
let result = ((28 + (28 + 7 * (totalWeeks - 1))) * totalWeeks) / 2;
算完週的部分再把其餘天數算出來並加起來,就是答案了
result += (days * (days + 1)) / 2 + days * totalWeeks;
return result;
心得
酷酷數學