LeetCode Entry
1716. Calculate Money in Leetcode Bank
Add increasing sum of money, drop weekly gain on mondays
1716. Calculate Money in Leetcode Bank easy blog post substack youtube

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/1153
Problem TLDR
Add increasing sum of money, drop weekly gain on mondays #easy
Intuition
Simulate.
// 0 1 2 3 4 5 6
// 7 8 9 10 11 12 13
// 14
// 1 2 3 4 5 6 7
// 2 3 4 5 6 7 8 or prev + 7
// 3 4 5 6 7 8 9 or prev + 7
// 4 5 6 7 8 9 10 or prev + 7
The O(1) solutino: count weeks and remainder of days.
Each week contributes as a sum of base7. Contribution of each bases is w(w-1)/2.
Another week contribution is weekly gains, 7*(7+1)/2. They are just w*gains
Approach
- draw the numbers to better understand the laws
Complexity
-
Time complexity: \(O(n)\) or O(1)
-
Space complexity: \(O(1)\)
Code
// 8ms
fun totalMoney(n: Int) = (0..<n).sumOf { it % 7 + it / 7 + 1 }
// 0ms
pub fn total_money(n: i32) -> i32 {
let w = n/7; let d = n-7*w;
let fullweeks = 28*w + 7*w*(w-1)/2;
let taildays = d*(d+1)/2 + w*d;
fullweeks + taildays
}