Leetcode 1716. Calculate Money in Leetcode Bank
Hercy wants to save money for his first car. He puts money in the Leetcode bank every day.
He starts by putting in 1 dollar on Monday, the first day. Every subsequent day, he will put in more money than the previous day by 1 dollar.
Every Monday, he will restart by putting 1 dollar in the Leetcode bank.
Given n, the total number of days Hercy will save money, return the total amount of money he will have in the Leetcode bank at the end of n days.
Input: n = 4
Output: 10
Explanation: After 4 days, the total money is 1 + 2 + 3 + 4 = 10.
Input: n = 10
Output: 37
Explanation: After 10 days, the total money is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (1 + 2 + 3) = 28 + 9 = 37.
Input: n = 20
Output: 96
Explanation: After 20 days, the total money is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (1 + 2 + 3 + 4 + 5 + 6 + 7) + (1 + 2 + 3 + 4 + 5 + 6) = 28 + 28 + 21 = 77.
n?
1 <= n <= 1000.n be zero or a negative number?
n is always a positive integer.n:
week = (day - 1) / 7.day_in_week = (day - 1) % 7.week + day_in_week + 1.n days.The algorithm will have a time complexity of O(n) since it iterates through each of the n days once.
#include <iostream>
#include <cmath>
class Solution {
public:
int totalMoney(int n) {
int total_money = 0;
for (int day = 1; day <= n; ++day) {
int week = (day - 1) / 7;
int day_in_week = (day - 1) % 7;
total_money += (week + day_in_week + 1);
}
return total_money;
}
};
int main() {
Solution solution;
int n;
// Example 1
n = 4;
std::cout << "Result for n = " << n << ": " << solution.totalMoney(n) << std::endl; // Output: 10
// Example 2
n = 10;
std::cout << "Result for n = " << n << ": " << solution.totalMoney(n) << std::endl; // Output: 37
// Example 3
n = 20;
std::cout << "Result for n = " << n << ": " << solution.totalMoney(n) << std::endl; // Output: 96
return 0;
}
This code initializes a total money counter, iterates through each day, calculates the savings increment correctly considering both week and day within the week, and sums up the total savings by the end of n days.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?