Leetcode 1716. Calculate Money in Leetcode Bank
You are given a bank account where you deposit money every day. The rules for the deposits are as follows:
1
dollar.1
dollar until the start of the next week (7 days later). On the eighth day, the deposit will be 1
dollar again, and then it will increase by 1
dollar each day again during that week.Given n
, the number of days, return the total money in the bank at the end of the nth day.
Q: Are the deposits reset to 1
dollar after every 7 days?
A: Yes, the deposit resets every week.
Q: Is n
guaranteed to be a positive integer?
A: Yes, n
is a positive integer.
totalMoney
to keep track of the total amount of money.1
to day n
:
week number + day of the week
.totalMoney
.totalMoney
.Here is the Java implementation of the strategy:
public class CalculateMoneyInBank {
public int totalMoney(int n) {
int totalMoney = 0; // Initialize total amount of money
for (int day = 1; day <= n; day++) {
int week = (day - 1) / 7; // Determine the week number
int dayOfWeek = (day - 1) % 7; // Determine the day of the week
totalMoney += week + dayOfWeek + 1; // Calculate deposit for the day
}
return totalMoney;
}
public static void main(String[] args) {
CalculateMoneyInBank bank = new CalculateMoneyInBank();
System.out.println(bank.totalMoney(10)); // Example test case
}
}
1
to n
(inclusive) where day
is the current day.week = (day - 1) / 7
: This gives the zero-based week number (0
for the first week, 1
for the second week, etc.).dayOfWeek = (day - 1) % 7
: This gives the zero-based day of the week (0
for Monday, 6
for Sunday).week + dayOfWeek + 1
.totalMoney
.1
to n
, performing constant-time operations within the loop.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?