|
| 1 | +// Source : https://leetcode.com/problems/calculate-money-in-leetcode-bank/ |
| 2 | +// Author : Hao Chen |
| 3 | +// Date : 2021-03-28 |
| 4 | + |
| 5 | +/***************************************************************************************************** |
| 6 | + * |
| 7 | + * Hercy wants to save money for his first car. He puts money in the Leetcode bank every day. |
| 8 | + * |
| 9 | + * He starts by putting in $1 on Monday, the first day. Every day from Tuesday to Sunday, he will put |
| 10 | + * in $1 more than the day before. On every subsequent Monday, he will put in $1 more than the |
| 11 | + * previous Monday. |
| 12 | + * |
| 13 | + * Given n, return the total amount of money he will have in the Leetcode bank at the end of the n^th |
| 14 | + * day. |
| 15 | + * |
| 16 | + * Example 1: |
| 17 | + * |
| 18 | + * Input: n = 4 |
| 19 | + * Output: 10 |
| 20 | + * Explanation: After the 4^th day, the total is 1 + 2 + 3 + 4 = 10. |
| 21 | + * |
| 22 | + * Example 2: |
| 23 | + * |
| 24 | + * Input: n = 10 |
| 25 | + * Output: 37 |
| 26 | + * Explanation: After the 10^th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. |
| 27 | + * Notice that on the 2^nd Monday, Hercy only puts in $2. |
| 28 | + * |
| 29 | + * Example 3: |
| 30 | + * |
| 31 | + * Input: n = 20 |
| 32 | + * Output: 96 |
| 33 | + * Explanation: After the 20^th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 |
| 34 | + * + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96. |
| 35 | + * |
| 36 | + * Constraints: |
| 37 | + * |
| 38 | + * 1 <= n <= 1000 |
| 39 | + ******************************************************************************************************/ |
| 40 | + |
| 41 | +class Solution { |
| 42 | +public: |
| 43 | + int totalMoney(int n) { |
| 44 | + int weeks = n / 7; |
| 45 | + int days = n % 7; |
| 46 | + |
| 47 | + int m = 1 + 2 + 3 + 4 + 5 + 6 + 7; |
| 48 | + // we know |
| 49 | + // week1 = 0*7 + m |
| 50 | + // week2 = 1*7 + m |
| 51 | + // week3 = 2*7 + m |
| 52 | + // weekn = (n-1)*7 + m |
| 53 | + // So, |
| 54 | + // week1 + week2 + week3 + ....+ weekn |
| 55 | + // = n*m + 7*(0+1+2+..n-1) |
| 56 | + // = n*m + 7*(n-1)*n/2 |
| 57 | + |
| 58 | + int money = weeks*m + 7 * (weeks-1) * weeks / 2; |
| 59 | + |
| 60 | + // for the rest days |
| 61 | + // every day needs to add previous `weeks * 1`, it is days* weeks |
| 62 | + // then add from 1 to days |
| 63 | + money += (days*weeks + days*(days+1)/2); |
| 64 | + |
| 65 | + return money; |
| 66 | + } |
| 67 | +}; |
0 commit comments