title
stringlengths
1
100
titleSlug
stringlengths
3
77
Java
int64
0
1
Python3
int64
1
1
content
stringlengths
28
44.4k
voteCount
int64
0
3.67k
question_content
stringlengths
65
5k
question_hints
stringclasses
970 values
Clean Code || O(N)
count-good-meals
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(22N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def countPairs(self, deliciousness: List[int]) -> int:\n count = {}\n res = 0\n MOD = pow(10, 9) + 7\n\n for rate in deliciousness:\n for i in range(22):\n sqr = pow(2, i)\n target = sqr - rate\n if target in count:\n res += count[target]\n if rate in count:\n count[rate] += 1\n else:\n count[rate] = 1\n \n return res % MOD\n```
2
You are given a string `s` (**0-indexed**)​​​​​​. You are asked to perform the following operation on `s`​​​​​​ until you get a sorted string: 1. Find **the largest index** `i` such that `1 <= i < s.length` and `s[i] < s[i - 1]`. 2. Find **the largest index** `j` such that `i <= j < s.length` and `s[k] < s[i - 1]` for all the possible values of `k` in the range `[i, j]` inclusive. 3. Swap the two characters at indices `i - 1`​​​​ and `j`​​​​​. 4. Reverse the suffix starting at index `i`​​​​​​. Return _the number of operations needed to make the string sorted._ Since the answer can be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** s = "cba " **Output:** 5 **Explanation:** The simulation goes as follows: Operation 1: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "cab ", then reverse the suffix starting at 2. Now, s= "cab ". Operation 2: i=1, j=2. Swap s\[0\] and s\[2\] to get s= "bac ", then reverse the suffix starting at 1. Now, s= "bca ". Operation 3: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "bac ", then reverse the suffix starting at 2. Now, s= "bac ". Operation 4: i=1, j=1. Swap s\[0\] and s\[1\] to get s= "abc ", then reverse the suffix starting at 1. Now, s= "acb ". Operation 5: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "abc ", then reverse the suffix starting at 2. Now, s= "abc ". **Example 2:** **Input:** s = "aabaa " **Output:** 2 **Explanation:** The simulation goes as follows: Operation 1: i=3, j=4. Swap s\[2\] and s\[4\] to get s= "aaaab ", then reverse the substring starting at 3. Now, s= "aaaba ". Operation 2: i=4, j=4. Swap s\[3\] and s\[4\] to get s= "aaaab ", then reverse the substring starting at 4. Now, s= "aaaab ". **Constraints:** * `1 <= s.length <= 3000` * `s`​​​​​​ consists only of lowercase English letters.
Note that the number of powers of 2 is at most 21 so this turns the problem to a classic find the number of pairs that sum to a certain value but for 21 values You need to use something fasters than the NlogN approach since there is already the log of iterating over the powers so one idea is two pointers
Count good meals - python
count-good-meals
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nexpending the 2sum question and noting there is only a small number of 2 powers (21) so it is not efficient to caculate it each time.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nfor items such i that i+i = 2^n we will just use 2 choose n the calculate the number of possabilities\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n# Code\n```\nfrom collections import defaultdict\n\n\nclass Solution:\n def countPairs(self, deliciousness: List[int]) -> int:\n \n uniqe_v = defaultdict(int)\n for i in deliciousness:\n uniqe_v[i] += 1\n \n\n power2 = set(2**i for i in range(21+1))\n\n dpower = {p:set() for p in power2}\n res = 0\n keys = list(uniqe_v.keys())\n for i in keys:\n for p, d in dpower.items():\n if i > p:\n continue\n\n if (p-i) in d:\n res += (uniqe_v[i]*uniqe_v[p-i])\n\n d.add(i)\n\n # i+i = 2^n\n if uniqe_v[i] > 1 and (i+i) in power2:\n # adding \'2 choose n\' \n res += ((uniqe_v[i]*(uniqe_v[i]-1))//2)\n\n return (res % (10**9 + 7))\n```
0
A **good meal** is a meal that contains **exactly two different food items** with a sum of deliciousness equal to a power of two. You can pick **any** two different foods to make a good meal. Given an array of integers `deliciousness` where `deliciousness[i]` is the deliciousness of the `i​​​​​​th​​​​`​​​​ item of food, return _the number of different **good meals** you can make from this list modulo_ `109 + 7`. Note that items with different indices are considered different even if they have the same deliciousness value. **Example 1:** **Input:** deliciousness = \[1,3,5,7,9\] **Output:** 4 **Explanation:** The good meals are (1,3), (1,7), (3,5) and, (7,9). Their respective sums are 4, 8, 8, and 16, all of which are powers of 2. **Example 2:** **Input:** deliciousness = \[1,1,1,3,3,3,7\] **Output:** 15 **Explanation:** The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways. **Constraints:** * `1 <= deliciousness.length <= 105` * `0 <= deliciousness[i] <= 220`
Find the smallest rowSum or colSum, and let it be x. Place that number in the grid, and subtract x from rowSum and colSum. Continue until all the sums are satisfied.
Count good meals - python
count-good-meals
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nexpending the 2sum question and noting there is only a small number of 2 powers (21) so it is not efficient to caculate it each time.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nfor items such i that i+i = 2^n we will just use 2 choose n the calculate the number of possabilities\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n# Code\n```\nfrom collections import defaultdict\n\n\nclass Solution:\n def countPairs(self, deliciousness: List[int]) -> int:\n \n uniqe_v = defaultdict(int)\n for i in deliciousness:\n uniqe_v[i] += 1\n \n\n power2 = set(2**i for i in range(21+1))\n\n dpower = {p:set() for p in power2}\n res = 0\n keys = list(uniqe_v.keys())\n for i in keys:\n for p, d in dpower.items():\n if i > p:\n continue\n\n if (p-i) in d:\n res += (uniqe_v[i]*uniqe_v[p-i])\n\n d.add(i)\n\n # i+i = 2^n\n if uniqe_v[i] > 1 and (i+i) in power2:\n # adding \'2 choose n\' \n res += ((uniqe_v[i]*(uniqe_v[i]-1))//2)\n\n return (res % (10**9 + 7))\n```
0
You are given a string `s` (**0-indexed**)​​​​​​. You are asked to perform the following operation on `s`​​​​​​ until you get a sorted string: 1. Find **the largest index** `i` such that `1 <= i < s.length` and `s[i] < s[i - 1]`. 2. Find **the largest index** `j` such that `i <= j < s.length` and `s[k] < s[i - 1]` for all the possible values of `k` in the range `[i, j]` inclusive. 3. Swap the two characters at indices `i - 1`​​​​ and `j`​​​​​. 4. Reverse the suffix starting at index `i`​​​​​​. Return _the number of operations needed to make the string sorted._ Since the answer can be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** s = "cba " **Output:** 5 **Explanation:** The simulation goes as follows: Operation 1: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "cab ", then reverse the suffix starting at 2. Now, s= "cab ". Operation 2: i=1, j=2. Swap s\[0\] and s\[2\] to get s= "bac ", then reverse the suffix starting at 1. Now, s= "bca ". Operation 3: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "bac ", then reverse the suffix starting at 2. Now, s= "bac ". Operation 4: i=1, j=1. Swap s\[0\] and s\[1\] to get s= "abc ", then reverse the suffix starting at 1. Now, s= "acb ". Operation 5: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "abc ", then reverse the suffix starting at 2. Now, s= "abc ". **Example 2:** **Input:** s = "aabaa " **Output:** 2 **Explanation:** The simulation goes as follows: Operation 1: i=3, j=4. Swap s\[2\] and s\[4\] to get s= "aaaab ", then reverse the substring starting at 3. Now, s= "aaaba ". Operation 2: i=4, j=4. Swap s\[3\] and s\[4\] to get s= "aaaab ", then reverse the substring starting at 4. Now, s= "aaaab ". **Constraints:** * `1 <= s.length <= 3000` * `s`​​​​​​ consists only of lowercase English letters.
Note that the number of powers of 2 is at most 21 so this turns the problem to a classic find the number of pairs that sum to a certain value but for 21 values You need to use something fasters than the NlogN approach since there is already the log of iterating over the powers so one idea is two pointers
Python3 solution
count-good-meals
0
1
\n# Code\n```\nclass Solution:\n def countPairs(self, deliciousness: List[int]) -> int:\n MOD = 10**9 + 7\n maxSum = max(deliciousness) * 2\n deliciousCount = {}\n deliciousMeals = 0\n\n for d in deliciousness:\n powerOfTwo = 1\n while powerOfTwo <= maxSum:\n complement = powerOfTwo - d\n deliciousMeals += deliciousCount.get(complement, 0)\n powerOfTwo *= 2\n \n deliciousCount[d] = deliciousCount.get(d, 0) + 1\n \n return deliciousMeals % MOD\n```
0
A **good meal** is a meal that contains **exactly two different food items** with a sum of deliciousness equal to a power of two. You can pick **any** two different foods to make a good meal. Given an array of integers `deliciousness` where `deliciousness[i]` is the deliciousness of the `i​​​​​​th​​​​`​​​​ item of food, return _the number of different **good meals** you can make from this list modulo_ `109 + 7`. Note that items with different indices are considered different even if they have the same deliciousness value. **Example 1:** **Input:** deliciousness = \[1,3,5,7,9\] **Output:** 4 **Explanation:** The good meals are (1,3), (1,7), (3,5) and, (7,9). Their respective sums are 4, 8, 8, and 16, all of which are powers of 2. **Example 2:** **Input:** deliciousness = \[1,1,1,3,3,3,7\] **Output:** 15 **Explanation:** The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways. **Constraints:** * `1 <= deliciousness.length <= 105` * `0 <= deliciousness[i] <= 220`
Find the smallest rowSum or colSum, and let it be x. Place that number in the grid, and subtract x from rowSum and colSum. Continue until all the sums are satisfied.
Python3 solution
count-good-meals
0
1
\n# Code\n```\nclass Solution:\n def countPairs(self, deliciousness: List[int]) -> int:\n MOD = 10**9 + 7\n maxSum = max(deliciousness) * 2\n deliciousCount = {}\n deliciousMeals = 0\n\n for d in deliciousness:\n powerOfTwo = 1\n while powerOfTwo <= maxSum:\n complement = powerOfTwo - d\n deliciousMeals += deliciousCount.get(complement, 0)\n powerOfTwo *= 2\n \n deliciousCount[d] = deliciousCount.get(d, 0) + 1\n \n return deliciousMeals % MOD\n```
0
You are given a string `s` (**0-indexed**)​​​​​​. You are asked to perform the following operation on `s`​​​​​​ until you get a sorted string: 1. Find **the largest index** `i` such that `1 <= i < s.length` and `s[i] < s[i - 1]`. 2. Find **the largest index** `j` such that `i <= j < s.length` and `s[k] < s[i - 1]` for all the possible values of `k` in the range `[i, j]` inclusive. 3. Swap the two characters at indices `i - 1`​​​​ and `j`​​​​​. 4. Reverse the suffix starting at index `i`​​​​​​. Return _the number of operations needed to make the string sorted._ Since the answer can be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** s = "cba " **Output:** 5 **Explanation:** The simulation goes as follows: Operation 1: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "cab ", then reverse the suffix starting at 2. Now, s= "cab ". Operation 2: i=1, j=2. Swap s\[0\] and s\[2\] to get s= "bac ", then reverse the suffix starting at 1. Now, s= "bca ". Operation 3: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "bac ", then reverse the suffix starting at 2. Now, s= "bac ". Operation 4: i=1, j=1. Swap s\[0\] and s\[1\] to get s= "abc ", then reverse the suffix starting at 1. Now, s= "acb ". Operation 5: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "abc ", then reverse the suffix starting at 2. Now, s= "abc ". **Example 2:** **Input:** s = "aabaa " **Output:** 2 **Explanation:** The simulation goes as follows: Operation 1: i=3, j=4. Swap s\[2\] and s\[4\] to get s= "aaaab ", then reverse the substring starting at 3. Now, s= "aaaba ". Operation 2: i=4, j=4. Swap s\[3\] and s\[4\] to get s= "aaaab ", then reverse the substring starting at 4. Now, s= "aaaab ". **Constraints:** * `1 <= s.length <= 3000` * `s`​​​​​​ consists only of lowercase English letters.
Note that the number of powers of 2 is at most 21 so this turns the problem to a classic find the number of pairs that sum to a certain value but for 21 values You need to use something fasters than the NlogN approach since there is already the log of iterating over the powers so one idea is two pointers
Simple python code beated 98%
count-good-meals
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def countPairs(self, deliciousness: List[int]) -> int:\n deliciousness_group_by = Counter(deliciousness)\n upper_bound = 22\n power2 = [(1 << i) for i in range(upper_bound)]\n ans = 0\n for delicious in deliciousness_group_by:\n left_index = bisect_left(power2, delicious)\n for index in range(left_index, upper_bound):\n left_over = power2[index] - delicious\n if left_over not in deliciousness_group_by:\n continue\n ans += deliciousness_group_by[delicious] * deliciousness_group_by[left_over] - (deliciousness_group_by[delicious] if delicious == left_over else 0)\n return (ans >> 1) % 100000000\n```
0
A **good meal** is a meal that contains **exactly two different food items** with a sum of deliciousness equal to a power of two. You can pick **any** two different foods to make a good meal. Given an array of integers `deliciousness` where `deliciousness[i]` is the deliciousness of the `i​​​​​​th​​​​`​​​​ item of food, return _the number of different **good meals** you can make from this list modulo_ `109 + 7`. Note that items with different indices are considered different even if they have the same deliciousness value. **Example 1:** **Input:** deliciousness = \[1,3,5,7,9\] **Output:** 4 **Explanation:** The good meals are (1,3), (1,7), (3,5) and, (7,9). Their respective sums are 4, 8, 8, and 16, all of which are powers of 2. **Example 2:** **Input:** deliciousness = \[1,1,1,3,3,3,7\] **Output:** 15 **Explanation:** The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways. **Constraints:** * `1 <= deliciousness.length <= 105` * `0 <= deliciousness[i] <= 220`
Find the smallest rowSum or colSum, and let it be x. Place that number in the grid, and subtract x from rowSum and colSum. Continue until all the sums are satisfied.
Simple python code beated 98%
count-good-meals
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def countPairs(self, deliciousness: List[int]) -> int:\n deliciousness_group_by = Counter(deliciousness)\n upper_bound = 22\n power2 = [(1 << i) for i in range(upper_bound)]\n ans = 0\n for delicious in deliciousness_group_by:\n left_index = bisect_left(power2, delicious)\n for index in range(left_index, upper_bound):\n left_over = power2[index] - delicious\n if left_over not in deliciousness_group_by:\n continue\n ans += deliciousness_group_by[delicious] * deliciousness_group_by[left_over] - (deliciousness_group_by[delicious] if delicious == left_over else 0)\n return (ans >> 1) % 100000000\n```
0
You are given a string `s` (**0-indexed**)​​​​​​. You are asked to perform the following operation on `s`​​​​​​ until you get a sorted string: 1. Find **the largest index** `i` such that `1 <= i < s.length` and `s[i] < s[i - 1]`. 2. Find **the largest index** `j` such that `i <= j < s.length` and `s[k] < s[i - 1]` for all the possible values of `k` in the range `[i, j]` inclusive. 3. Swap the two characters at indices `i - 1`​​​​ and `j`​​​​​. 4. Reverse the suffix starting at index `i`​​​​​​. Return _the number of operations needed to make the string sorted._ Since the answer can be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** s = "cba " **Output:** 5 **Explanation:** The simulation goes as follows: Operation 1: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "cab ", then reverse the suffix starting at 2. Now, s= "cab ". Operation 2: i=1, j=2. Swap s\[0\] and s\[2\] to get s= "bac ", then reverse the suffix starting at 1. Now, s= "bca ". Operation 3: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "bac ", then reverse the suffix starting at 2. Now, s= "bac ". Operation 4: i=1, j=1. Swap s\[0\] and s\[1\] to get s= "abc ", then reverse the suffix starting at 1. Now, s= "acb ". Operation 5: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "abc ", then reverse the suffix starting at 2. Now, s= "abc ". **Example 2:** **Input:** s = "aabaa " **Output:** 2 **Explanation:** The simulation goes as follows: Operation 1: i=3, j=4. Swap s\[2\] and s\[4\] to get s= "aaaab ", then reverse the substring starting at 3. Now, s= "aaaba ". Operation 2: i=4, j=4. Swap s\[3\] and s\[4\] to get s= "aaaab ", then reverse the substring starting at 4. Now, s= "aaaab ". **Constraints:** * `1 <= s.length <= 3000` * `s`​​​​​​ consists only of lowercase English letters.
Note that the number of powers of 2 is at most 21 so this turns the problem to a classic find the number of pairs that sum to a certain value but for 21 values You need to use something fasters than the NlogN approach since there is already the log of iterating over the powers so one idea is two pointers
Python - 5 lines, variation of 2 sum
count-good-meals
0
1
# Intuition\nSame idea as in hash table based 2 sum. Difference is, here one needs to find previously seen value that sum up to some power of 2, To speed up power of 2 match, precompute powers of 2.\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nclass Solution:\n def countPairs(self, deliciousness: List[int]) -> int:\n occ, mod, result, powers = Counter(), 1_000_000_007, 0, [2**i for i in range(24)]\n for v in deliciousness:\n for p in powers: result = (result + occ[p-v]) % mod\n occ[v] += 1\n return result\n \n```
0
A **good meal** is a meal that contains **exactly two different food items** with a sum of deliciousness equal to a power of two. You can pick **any** two different foods to make a good meal. Given an array of integers `deliciousness` where `deliciousness[i]` is the deliciousness of the `i​​​​​​th​​​​`​​​​ item of food, return _the number of different **good meals** you can make from this list modulo_ `109 + 7`. Note that items with different indices are considered different even if they have the same deliciousness value. **Example 1:** **Input:** deliciousness = \[1,3,5,7,9\] **Output:** 4 **Explanation:** The good meals are (1,3), (1,7), (3,5) and, (7,9). Their respective sums are 4, 8, 8, and 16, all of which are powers of 2. **Example 2:** **Input:** deliciousness = \[1,1,1,3,3,3,7\] **Output:** 15 **Explanation:** The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways. **Constraints:** * `1 <= deliciousness.length <= 105` * `0 <= deliciousness[i] <= 220`
Find the smallest rowSum or colSum, and let it be x. Place that number in the grid, and subtract x from rowSum and colSum. Continue until all the sums are satisfied.
Python - 5 lines, variation of 2 sum
count-good-meals
0
1
# Intuition\nSame idea as in hash table based 2 sum. Difference is, here one needs to find previously seen value that sum up to some power of 2, To speed up power of 2 match, precompute powers of 2.\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nclass Solution:\n def countPairs(self, deliciousness: List[int]) -> int:\n occ, mod, result, powers = Counter(), 1_000_000_007, 0, [2**i for i in range(24)]\n for v in deliciousness:\n for p in powers: result = (result + occ[p-v]) % mod\n occ[v] += 1\n return result\n \n```
0
You are given a string `s` (**0-indexed**)​​​​​​. You are asked to perform the following operation on `s`​​​​​​ until you get a sorted string: 1. Find **the largest index** `i` such that `1 <= i < s.length` and `s[i] < s[i - 1]`. 2. Find **the largest index** `j` such that `i <= j < s.length` and `s[k] < s[i - 1]` for all the possible values of `k` in the range `[i, j]` inclusive. 3. Swap the two characters at indices `i - 1`​​​​ and `j`​​​​​. 4. Reverse the suffix starting at index `i`​​​​​​. Return _the number of operations needed to make the string sorted._ Since the answer can be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** s = "cba " **Output:** 5 **Explanation:** The simulation goes as follows: Operation 1: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "cab ", then reverse the suffix starting at 2. Now, s= "cab ". Operation 2: i=1, j=2. Swap s\[0\] and s\[2\] to get s= "bac ", then reverse the suffix starting at 1. Now, s= "bca ". Operation 3: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "bac ", then reverse the suffix starting at 2. Now, s= "bac ". Operation 4: i=1, j=1. Swap s\[0\] and s\[1\] to get s= "abc ", then reverse the suffix starting at 1. Now, s= "acb ". Operation 5: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "abc ", then reverse the suffix starting at 2. Now, s= "abc ". **Example 2:** **Input:** s = "aabaa " **Output:** 2 **Explanation:** The simulation goes as follows: Operation 1: i=3, j=4. Swap s\[2\] and s\[4\] to get s= "aaaab ", then reverse the substring starting at 3. Now, s= "aaaba ". Operation 2: i=4, j=4. Swap s\[3\] and s\[4\] to get s= "aaaab ", then reverse the substring starting at 4. Now, s= "aaaab ". **Constraints:** * `1 <= s.length <= 3000` * `s`​​​​​​ consists only of lowercase English letters.
Note that the number of powers of 2 is at most 21 so this turns the problem to a classic find the number of pairs that sum to a certain value but for 21 values You need to use something fasters than the NlogN approach since there is already the log of iterating over the powers so one idea is two pointers
Python Very Simple
count-good-meals
0
1
# Intuition / Approach\nLike two sum, iterate though the ints and keep a hash map of old ints to check if current int will sum with previous int to equal a target.Iterate through the targets which are possible powers of 2 to sum up matches for each of the ints.\n\n# Complexity\n$$O(n)$$\n\n# Code\n```\nclass Solution:\n def countPairs(self, deliciousness: List[int]) -> int:\n ans = 0; m={}\n for d in deliciousness:\n for i in range(22): ans += m.get(math.pow(2,i)-d, 0)\n m[d]=m.get(d,0)+1\n return int(ans % (7+1e9))\n```
0
A **good meal** is a meal that contains **exactly two different food items** with a sum of deliciousness equal to a power of two. You can pick **any** two different foods to make a good meal. Given an array of integers `deliciousness` where `deliciousness[i]` is the deliciousness of the `i​​​​​​th​​​​`​​​​ item of food, return _the number of different **good meals** you can make from this list modulo_ `109 + 7`. Note that items with different indices are considered different even if they have the same deliciousness value. **Example 1:** **Input:** deliciousness = \[1,3,5,7,9\] **Output:** 4 **Explanation:** The good meals are (1,3), (1,7), (3,5) and, (7,9). Their respective sums are 4, 8, 8, and 16, all of which are powers of 2. **Example 2:** **Input:** deliciousness = \[1,1,1,3,3,3,7\] **Output:** 15 **Explanation:** The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways. **Constraints:** * `1 <= deliciousness.length <= 105` * `0 <= deliciousness[i] <= 220`
Find the smallest rowSum or colSum, and let it be x. Place that number in the grid, and subtract x from rowSum and colSum. Continue until all the sums are satisfied.
Python Very Simple
count-good-meals
0
1
# Intuition / Approach\nLike two sum, iterate though the ints and keep a hash map of old ints to check if current int will sum with previous int to equal a target.Iterate through the targets which are possible powers of 2 to sum up matches for each of the ints.\n\n# Complexity\n$$O(n)$$\n\n# Code\n```\nclass Solution:\n def countPairs(self, deliciousness: List[int]) -> int:\n ans = 0; m={}\n for d in deliciousness:\n for i in range(22): ans += m.get(math.pow(2,i)-d, 0)\n m[d]=m.get(d,0)+1\n return int(ans % (7+1e9))\n```
0
You are given a string `s` (**0-indexed**)​​​​​​. You are asked to perform the following operation on `s`​​​​​​ until you get a sorted string: 1. Find **the largest index** `i` such that `1 <= i < s.length` and `s[i] < s[i - 1]`. 2. Find **the largest index** `j` such that `i <= j < s.length` and `s[k] < s[i - 1]` for all the possible values of `k` in the range `[i, j]` inclusive. 3. Swap the two characters at indices `i - 1`​​​​ and `j`​​​​​. 4. Reverse the suffix starting at index `i`​​​​​​. Return _the number of operations needed to make the string sorted._ Since the answer can be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** s = "cba " **Output:** 5 **Explanation:** The simulation goes as follows: Operation 1: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "cab ", then reverse the suffix starting at 2. Now, s= "cab ". Operation 2: i=1, j=2. Swap s\[0\] and s\[2\] to get s= "bac ", then reverse the suffix starting at 1. Now, s= "bca ". Operation 3: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "bac ", then reverse the suffix starting at 2. Now, s= "bac ". Operation 4: i=1, j=1. Swap s\[0\] and s\[1\] to get s= "abc ", then reverse the suffix starting at 1. Now, s= "acb ". Operation 5: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "abc ", then reverse the suffix starting at 2. Now, s= "abc ". **Example 2:** **Input:** s = "aabaa " **Output:** 2 **Explanation:** The simulation goes as follows: Operation 1: i=3, j=4. Swap s\[2\] and s\[4\] to get s= "aaaab ", then reverse the substring starting at 3. Now, s= "aaaba ". Operation 2: i=4, j=4. Swap s\[3\] and s\[4\] to get s= "aaaab ", then reverse the substring starting at 4. Now, s= "aaaab ". **Constraints:** * `1 <= s.length <= 3000` * `s`​​​​​​ consists only of lowercase English letters.
Note that the number of powers of 2 is at most 21 so this turns the problem to a classic find the number of pairs that sum to a certain value but for 21 values You need to use something fasters than the NlogN approach since there is already the log of iterating over the powers so one idea is two pointers
How much is this different from 2sum? Hashtable runnig up to 22 times
count-good-meals
0
1
# Code\n```\nclass Solution:\n def countPairs(self, deliciousness: List[int]) -> int:\n deliciousness.sort()\n res = 0\n for i in range(22):\n target = 2**i\n if max(deliciousness)*2 < target: break \n freq = {}\n for a in deliciousness:\n if a > target:\n break\n if target - a in freq:\n res += freq[target-a]\n if a not in freq:\n freq[a] = 0\n freq[a] += 1\n return res % (10**9+7)\n```
0
A **good meal** is a meal that contains **exactly two different food items** with a sum of deliciousness equal to a power of two. You can pick **any** two different foods to make a good meal. Given an array of integers `deliciousness` where `deliciousness[i]` is the deliciousness of the `i​​​​​​th​​​​`​​​​ item of food, return _the number of different **good meals** you can make from this list modulo_ `109 + 7`. Note that items with different indices are considered different even if they have the same deliciousness value. **Example 1:** **Input:** deliciousness = \[1,3,5,7,9\] **Output:** 4 **Explanation:** The good meals are (1,3), (1,7), (3,5) and, (7,9). Their respective sums are 4, 8, 8, and 16, all of which are powers of 2. **Example 2:** **Input:** deliciousness = \[1,1,1,3,3,3,7\] **Output:** 15 **Explanation:** The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways. **Constraints:** * `1 <= deliciousness.length <= 105` * `0 <= deliciousness[i] <= 220`
Find the smallest rowSum or colSum, and let it be x. Place that number in the grid, and subtract x from rowSum and colSum. Continue until all the sums are satisfied.
How much is this different from 2sum? Hashtable runnig up to 22 times
count-good-meals
0
1
# Code\n```\nclass Solution:\n def countPairs(self, deliciousness: List[int]) -> int:\n deliciousness.sort()\n res = 0\n for i in range(22):\n target = 2**i\n if max(deliciousness)*2 < target: break \n freq = {}\n for a in deliciousness:\n if a > target:\n break\n if target - a in freq:\n res += freq[target-a]\n if a not in freq:\n freq[a] = 0\n freq[a] += 1\n return res % (10**9+7)\n```
0
You are given a string `s` (**0-indexed**)​​​​​​. You are asked to perform the following operation on `s`​​​​​​ until you get a sorted string: 1. Find **the largest index** `i` such that `1 <= i < s.length` and `s[i] < s[i - 1]`. 2. Find **the largest index** `j` such that `i <= j < s.length` and `s[k] < s[i - 1]` for all the possible values of `k` in the range `[i, j]` inclusive. 3. Swap the two characters at indices `i - 1`​​​​ and `j`​​​​​. 4. Reverse the suffix starting at index `i`​​​​​​. Return _the number of operations needed to make the string sorted._ Since the answer can be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** s = "cba " **Output:** 5 **Explanation:** The simulation goes as follows: Operation 1: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "cab ", then reverse the suffix starting at 2. Now, s= "cab ". Operation 2: i=1, j=2. Swap s\[0\] and s\[2\] to get s= "bac ", then reverse the suffix starting at 1. Now, s= "bca ". Operation 3: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "bac ", then reverse the suffix starting at 2. Now, s= "bac ". Operation 4: i=1, j=1. Swap s\[0\] and s\[1\] to get s= "abc ", then reverse the suffix starting at 1. Now, s= "acb ". Operation 5: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "abc ", then reverse the suffix starting at 2. Now, s= "abc ". **Example 2:** **Input:** s = "aabaa " **Output:** 2 **Explanation:** The simulation goes as follows: Operation 1: i=3, j=4. Swap s\[2\] and s\[4\] to get s= "aaaab ", then reverse the substring starting at 3. Now, s= "aaaba ". Operation 2: i=4, j=4. Swap s\[3\] and s\[4\] to get s= "aaaab ", then reverse the substring starting at 4. Now, s= "aaaab ". **Constraints:** * `1 <= s.length <= 3000` * `s`​​​​​​ consists only of lowercase English letters.
Note that the number of powers of 2 is at most 21 so this turns the problem to a classic find the number of pairs that sum to a certain value but for 21 values You need to use something fasters than the NlogN approach since there is already the log of iterating over the powers so one idea is two pointers
very simple solution like Leetcode 1 || Python
count-good-meals
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def countPairs(self, deliciousness: List[int]) -> int:\n # devide the result by modulo in the question \n ct=0\n my_dict={}\n for i in range(len(deliciousness)):\n for n in range(22):\n b=2**n - deliciousness[i]\n if b in my_dict:\n ct+=my_dict[b]\n my_dict[deliciousness[i]]=1+my_dict.get(deliciousness[i],0)\n\n return ct%(10**9+7) # devide the result by modulo in the question \n```
0
A **good meal** is a meal that contains **exactly two different food items** with a sum of deliciousness equal to a power of two. You can pick **any** two different foods to make a good meal. Given an array of integers `deliciousness` where `deliciousness[i]` is the deliciousness of the `i​​​​​​th​​​​`​​​​ item of food, return _the number of different **good meals** you can make from this list modulo_ `109 + 7`. Note that items with different indices are considered different even if they have the same deliciousness value. **Example 1:** **Input:** deliciousness = \[1,3,5,7,9\] **Output:** 4 **Explanation:** The good meals are (1,3), (1,7), (3,5) and, (7,9). Their respective sums are 4, 8, 8, and 16, all of which are powers of 2. **Example 2:** **Input:** deliciousness = \[1,1,1,3,3,3,7\] **Output:** 15 **Explanation:** The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways. **Constraints:** * `1 <= deliciousness.length <= 105` * `0 <= deliciousness[i] <= 220`
Find the smallest rowSum or colSum, and let it be x. Place that number in the grid, and subtract x from rowSum and colSum. Continue until all the sums are satisfied.
very simple solution like Leetcode 1 || Python
count-good-meals
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def countPairs(self, deliciousness: List[int]) -> int:\n # devide the result by modulo in the question \n ct=0\n my_dict={}\n for i in range(len(deliciousness)):\n for n in range(22):\n b=2**n - deliciousness[i]\n if b in my_dict:\n ct+=my_dict[b]\n my_dict[deliciousness[i]]=1+my_dict.get(deliciousness[i],0)\n\n return ct%(10**9+7) # devide the result by modulo in the question \n```
0
You are given a string `s` (**0-indexed**)​​​​​​. You are asked to perform the following operation on `s`​​​​​​ until you get a sorted string: 1. Find **the largest index** `i` such that `1 <= i < s.length` and `s[i] < s[i - 1]`. 2. Find **the largest index** `j` such that `i <= j < s.length` and `s[k] < s[i - 1]` for all the possible values of `k` in the range `[i, j]` inclusive. 3. Swap the two characters at indices `i - 1`​​​​ and `j`​​​​​. 4. Reverse the suffix starting at index `i`​​​​​​. Return _the number of operations needed to make the string sorted._ Since the answer can be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** s = "cba " **Output:** 5 **Explanation:** The simulation goes as follows: Operation 1: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "cab ", then reverse the suffix starting at 2. Now, s= "cab ". Operation 2: i=1, j=2. Swap s\[0\] and s\[2\] to get s= "bac ", then reverse the suffix starting at 1. Now, s= "bca ". Operation 3: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "bac ", then reverse the suffix starting at 2. Now, s= "bac ". Operation 4: i=1, j=1. Swap s\[0\] and s\[1\] to get s= "abc ", then reverse the suffix starting at 1. Now, s= "acb ". Operation 5: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "abc ", then reverse the suffix starting at 2. Now, s= "abc ". **Example 2:** **Input:** s = "aabaa " **Output:** 2 **Explanation:** The simulation goes as follows: Operation 1: i=3, j=4. Swap s\[2\] and s\[4\] to get s= "aaaab ", then reverse the substring starting at 3. Now, s= "aaaba ". Operation 2: i=4, j=4. Swap s\[3\] and s\[4\] to get s= "aaaab ", then reverse the substring starting at 4. Now, s= "aaaab ". **Constraints:** * `1 <= s.length <= 3000` * `s`​​​​​​ consists only of lowercase English letters.
Note that the number of powers of 2 is at most 21 so this turns the problem to a classic find the number of pairs that sum to a certain value but for 21 values You need to use something fasters than the NlogN approach since there is already the log of iterating over the powers so one idea is two pointers
[Python3] binary search & 2-pointer
ways-to-split-array-into-three-subarrays
0
1
**Algo**\nCompute prefix array of `nums`. Any at index `i`, you want to find index `j` such at \n`prefix[i] <= prefix[j] - prefix[i] <= prefix[-1] - prefix[j]`\nThe rest comes out naturally. \n\n**Implementation** \n```\nclass Solution:\n def waysToSplit(self, nums: List[int]) -> int:\n prefix = [0]\n for x in nums: prefix.append(prefix[-1] + x)\n \n ans = 0\n for i in range(1, len(nums)): \n j = bisect_left(prefix, 2*prefix[i])\n k = bisect_right(prefix, (prefix[i] + prefix[-1])//2)\n ans += max(0, min(len(nums), k) - max(i+1, j))\n return ans % 1_000_000_007\n```\n\n**Analysis**\nTime complexity `O(NlogN)`\nSpace complexity `O(N)`\n\nEdit\nAdding two pointers approach `O(N)` time\n```\nclass Solution:\n def waysToSplit(self, nums: List[int]) -> int:\n prefix = [0]\n for x in nums: prefix.append(prefix[-1] + x)\n \n ans = j = k = 0 \n for i in range(1, len(nums)): \n j = max(j, i+1)\n while j < len(nums) and 2*prefix[i] > prefix[j]: j += 1\n k = max(k, j)\n while k < len(nums) and 2*prefix[k] <= prefix[i] + prefix[-1]: k += 1\n ans += k - j \n return ans % 1_000_000_007\n```
76
A split of an integer array is **good** if: * The array is split into three **non-empty** contiguous subarrays - named `left`, `mid`, `right` respectively from left to right. * The sum of the elements in `left` is less than or equal to the sum of the elements in `mid`, and the sum of the elements in `mid` is less than or equal to the sum of the elements in `right`. Given `nums`, an array of **non-negative** integers, return _the number of **good** ways to split_ `nums`. As the number may be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** nums = \[1,1,1\] **Output:** 1 **Explanation:** The only good way to split nums is \[1\] \[1\] \[1\]. **Example 2:** **Input:** nums = \[1,2,2,2,5,0\] **Output:** 3 **Explanation:** There are three good ways of splitting nums: \[1\] \[2\] \[2,2,5,0\] \[1\] \[2,2\] \[2,5,0\] \[1,2\] \[2,2\] \[5,0\] **Example 3:** **Input:** nums = \[3,2,1\] **Output:** 0 **Explanation:** There is no good way to split nums. **Constraints:** * `3 <= nums.length <= 105` * `0 <= nums[i] <= 104`
null
Python 3 | Binary Search | Explanation
ways-to-split-array-into-three-subarrays
0
1
### Explanation\n- Calculate prefix sum and store at `pre_sum`\n- Iterate each index `i` and consider it as the ending index of the 1st segment\n- Do _**binary search**_ on the 2nd segment ending index. This is doable because `pre_sum` is a non-decreasing array\n\t- `[i+1, j]` is the shortest possible segment of the 2nd segment (`bisect_left`)\n\t\t- Condition to find: `pre_sum[i] * 2 <= pre_sum[j]`\n\t\t- Meaning the 2nd segment sum will not be less than the 1st segment sum\n\t- `[i+1, k-1]` is the longest possible segment of the 2nd segment (`bisect_right`)\n\t\t- Condition to find: `pre_sum[k-1] - pre_sum[i] <= pre_sum[-1] - pre_sum[k-1]`\n\t\t- Meaning the 3rd segment sum will not be less than the 2dn segment sum\n\t- For example, all combinations below will be acceptable\n\t```\n\t\t\t# [0, i], [i+1, j], [j+1, n-1]\n\t\t\t# [0, i], [i+1, j+1], [j+2, n-1]\n\t\t\t# [0, i], [i+1, ...], [..., n-1]\n\t\t\t# [0, i], [i+1, k-2], [k-1, n-1]\n\t\t\t# [0, i], [i+1, k-1], [k, n-1]\n\t```\n- Don\'t forget to handle the edge case when `k == n`\n- Time: `O(NlogN)`\n- Space: `O(N)`\n### Implementation\n```\nclass Solution:\n def waysToSplit(self, nums: List[int]) -> int:\n mod, pre_sum = int(1e9+7), [nums[0]]\n for num in nums[1:]: # create prefix sum array\n pre_sum.append(pre_sum[-1] + num)\n ans, n = 0, len(nums)\n for i in range(n): # pre_sum[i] is the sum of the 1st segment\n prev = pre_sum[i] # i+1 is the starting index of the 2nd segment\n if prev * 3 > pre_sum[-1]: break # break loop if first segment is larger than the sum of 2 & 3 segments\n \n j = bisect.bisect_left(pre_sum, prev * 2, i+1) # j is the first possible ending index of 2nd segment\n \n middle = (prev + pre_sum[-1]) // 2 # last possible ending value of 2nd segment\n k = bisect.bisect_right(pre_sum, middle, j+1) # k-1 is the last possible ending index of 2nd segment\n if k-1 >= n or pre_sum[k-1] > middle: continue # make sure the value satisfy the condition since we are using bisect_right here\n ans = (ans + min(k, n - 1) - j) % mod # count & handle edge case\n return ans\n```
23
A split of an integer array is **good** if: * The array is split into three **non-empty** contiguous subarrays - named `left`, `mid`, `right` respectively from left to right. * The sum of the elements in `left` is less than or equal to the sum of the elements in `mid`, and the sum of the elements in `mid` is less than or equal to the sum of the elements in `right`. Given `nums`, an array of **non-negative** integers, return _the number of **good** ways to split_ `nums`. As the number may be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** nums = \[1,1,1\] **Output:** 1 **Explanation:** The only good way to split nums is \[1\] \[1\] \[1\]. **Example 2:** **Input:** nums = \[1,2,2,2,5,0\] **Output:** 3 **Explanation:** There are three good ways of splitting nums: \[1\] \[2\] \[2,2,5,0\] \[1\] \[2,2\] \[2,5,0\] \[1,2\] \[2,2\] \[5,0\] **Example 3:** **Input:** nums = \[3,2,1\] **Output:** 0 **Explanation:** There is no good way to split nums. **Constraints:** * `3 <= nums.length <= 105` * `0 <= nums[i] <= 104`
null
📌📌 Well-Coded || Both Method || Two-Pointer || Binary Search 🐍
ways-to-split-array-into-three-subarrays
0
1
## IDEA:\n\n**Two Pointers :**\n\'\'\'\n\n\tclass Solution:\n def waysToSplit(self, nums: List[int]) -> int:\n \n MOD = 10**9 + 7\n n = len(nums)\n for i in range(1,n):\n nums[i]+=nums[i-1]\n \n res,j,k = 0,0,0\n for i in range(n-2):\n if j<=i:\n j = i+1\n while j<n-1 and nums[i]>nums[j]-nums[i]:\n j+=1\n \n\t\t\tif k<j:\n k = j\n while k<n-1 and nums[k]-nums[i]<=nums[n-1]-nums[k]:\n k += 1\n res = (res + k - j)%MOD\n \n return res\n\n****\n**Using Binary Search :**\n\'\'\'\n\n\tclass Solution:\n def waysToSplit(self, nums: List[int]) -> int:\n mod, pre_sum = int(1e9+7), [nums[0]]\n for num in nums[1:]: # create prefix sum array\n pre_sum.append(pre_sum[-1] + num)\n ans, n = 0, len(nums)\n for i in range(n): # pre_sum[i] is the sum of the 1st segment\n prev = pre_sum[i] # i+1 is the starting index of the 2nd segment\n if prev * 3 > pre_sum[-1]: break # break loop if first segment is larger than the sum of 2 & 3 segments\n \n j = bisect.bisect_left(pre_sum, prev * 2, i+1) # j is the first possible ending index of 2nd segment\n \n middle = (prev + pre_sum[-1]) // 2 # last possible ending value of 2nd segment\n k = bisect.bisect_right(pre_sum, middle, j+1) # k-1 is the last possible ending index of 2nd segment\n if k-1 >= n or pre_sum[k-1] > middle: continue # make sure the value satisfy the condition since we are using bisect_right here\n ans = (ans + min(k, n - 1) - j) % mod # count & handle edge case\n return ans\n\n### Thanks and Upvote if you got any help!!\uD83E\uDD1E
3
A split of an integer array is **good** if: * The array is split into three **non-empty** contiguous subarrays - named `left`, `mid`, `right` respectively from left to right. * The sum of the elements in `left` is less than or equal to the sum of the elements in `mid`, and the sum of the elements in `mid` is less than or equal to the sum of the elements in `right`. Given `nums`, an array of **non-negative** integers, return _the number of **good** ways to split_ `nums`. As the number may be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** nums = \[1,1,1\] **Output:** 1 **Explanation:** The only good way to split nums is \[1\] \[1\] \[1\]. **Example 2:** **Input:** nums = \[1,2,2,2,5,0\] **Output:** 3 **Explanation:** There are three good ways of splitting nums: \[1\] \[2\] \[2,2,5,0\] \[1\] \[2,2\] \[2,5,0\] \[1,2\] \[2,2\] \[5,0\] **Example 3:** **Input:** nums = \[3,2,1\] **Output:** 0 **Explanation:** There is no good way to split nums. **Constraints:** * `3 <= nums.length <= 105` * `0 <= nums[i] <= 104`
null
intuitive (at least relatively intuitive) binary search
ways-to-split-array-into-three-subarrays
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis is actually a really hard problem with many edge cases (in my opinion). \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFirst thing we can note is that the elements of the array are going to be non-negative. This means even though the array itself might not be sorted, the prefix sum will be sorted. This means we can use binary search to help us.\n\nWe Iterate through the array, with each iteration representing where we are considering the first subarray to end. Then, we use binary search on the prefix sum to find the FIRST possible index where the second array can end (sum of second subarray > sum of first subarray). Then we use binary search AGAIN to find the LAST possible index of second array. \n\nThen we simply add up the difference in the start and end indexes to the count / result variable. My implementation might be a bit messy but the idea is what i shared above. \n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(nlogn)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```\nclass Solution:\n def waysToSplit(self, nums: List[int]) -> int:\n #prefix sum, \n #since non negative integers, prefix sum will be sorted\n def binarySearch(target, left, right):\n ans = -1\n while left <= right:\n middle = (left+right) // 2\n \n if prefix[middle]>= target:\n ans = middle\n right = middle - 1\n else:\n left = middle + 1\n return ans \n\n\n\n count = 0\n prefix = [0]*len(nums)\n for i in range(len(nums)):\n if i == 0:\n prefix[i] = nums[i]\n else:\n prefix[i] = nums[i] + prefix[i-1]\n totalSum = prefix[-1]\n\n for i in range(len(nums) - 2):\n currSum = prefix[i]\n #calculate remaining Sum removing until curr \n remaining = totalSum - currSum\n startVal = currSum\n if remaining % 2 == 0:\n endVal = remaining // 2 + 1\n else:\n endVal = ceil(remaining / 2)\n \n secondStartIndex = binarySearch(currSum*2, i+1, len(nums)-2)\n if secondStartIndex == -1:\n continue\n thirdSum = totalSum - prefix[secondStartIndex]\n secondSum = prefix[secondStartIndex] - prefix[i]\n if remaining != 0 and secondSum > remaining // 2:\n continue\n else:\n maxSecondIndex = binarySearch(currSum+endVal, i+1, len(nums)-1)\n \n thirdSum = totalSum - prefix[maxSecondIndex]\n if maxSecondIndex == secondStartIndex:\n count += 1\n elif maxSecondIndex == -1:\n maxSecondIndex = len(nums) - 1\n count += maxSecondIndex - secondStartIndex \n \n return count %(10**9 + 7)\n \n```
0
A split of an integer array is **good** if: * The array is split into three **non-empty** contiguous subarrays - named `left`, `mid`, `right` respectively from left to right. * The sum of the elements in `left` is less than or equal to the sum of the elements in `mid`, and the sum of the elements in `mid` is less than or equal to the sum of the elements in `right`. Given `nums`, an array of **non-negative** integers, return _the number of **good** ways to split_ `nums`. As the number may be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** nums = \[1,1,1\] **Output:** 1 **Explanation:** The only good way to split nums is \[1\] \[1\] \[1\]. **Example 2:** **Input:** nums = \[1,2,2,2,5,0\] **Output:** 3 **Explanation:** There are three good ways of splitting nums: \[1\] \[2\] \[2,2,5,0\] \[1\] \[2,2\] \[2,5,0\] \[1,2\] \[2,2\] \[5,0\] **Example 3:** **Input:** nums = \[3,2,1\] **Output:** 0 **Explanation:** There is no good way to split nums. **Constraints:** * `3 <= nums.length <= 105` * `0 <= nums[i] <= 104`
null
Python 3 solution
ways-to-split-array-into-three-subarrays
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def waysToSplit(self, nums: List[int]) -> int:\n kMod = 1_000_000_007\n n = len(nums)\n ans = 0\n prefix = list(itertools.accumulate(nums))\n\n # Find the first index j s.t.\n # Mid = prefix[j] - prefix[i] >= left = prefix[i]\n def firstGreaterEqual(i: int) -> int:\n l = i + 1\n r = n - 1\n while l < r:\n m = (l + r) // 2\n if prefix[m] - prefix[i] >= prefix[i]:\n r = m\n else:\n l = m + 1\n return l\n\n # Find the first index k s.t.\n # Mid = prefix[k] - prefix[i] > right = prefix[-1] - prefix[k]\n def firstGreater(i: int) -> int:\n l = i + 1\n r = n - 1\n while l < r:\n m = (l + r) // 2\n if prefix[m] - prefix[i] > prefix[-1] - prefix[m]:\n r = m\n else:\n l = m + 1\n return l\n\n for i in range(n - 2):\n j = firstGreaterEqual(i)\n if j == n - 1:\n break\n mid = prefix[j] - prefix[i]\n right = prefix[-1] - prefix[j]\n if mid > right:\n continue\n k = firstGreater(i)\n ans = (ans + k - j) % kMod\n\n return ans\n\n```
0
A split of an integer array is **good** if: * The array is split into three **non-empty** contiguous subarrays - named `left`, `mid`, `right` respectively from left to right. * The sum of the elements in `left` is less than or equal to the sum of the elements in `mid`, and the sum of the elements in `mid` is less than or equal to the sum of the elements in `right`. Given `nums`, an array of **non-negative** integers, return _the number of **good** ways to split_ `nums`. As the number may be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** nums = \[1,1,1\] **Output:** 1 **Explanation:** The only good way to split nums is \[1\] \[1\] \[1\]. **Example 2:** **Input:** nums = \[1,2,2,2,5,0\] **Output:** 3 **Explanation:** There are three good ways of splitting nums: \[1\] \[2\] \[2,2,5,0\] \[1\] \[2,2\] \[2,5,0\] \[1,2\] \[2,2\] \[5,0\] **Example 3:** **Input:** nums = \[3,2,1\] **Output:** 0 **Explanation:** There is no good way to split nums. **Constraints:** * `3 <= nums.length <= 105` * `0 <= nums[i] <= 104`
null
✔ Python3 Solution | LIS
minimum-operations-to-make-a-subsequence
0
1
```\nclass Solution:\n def minOperations(self, target, arr):\n n, nums = len(target), []\n D = {target[i]: i for i in range(n)}\n res = [D[i] for i in arr if i in D.keys()]\n for i in res:\n j = bisect.bisect_left(nums, i)\n if j == len(nums): nums.append(i)\n else: nums[j] = i\n return n - len(nums)\n```
1
You are given an array `target` that consists of **distinct** integers and another integer array `arr` that **can** have duplicates. In one operation, you can insert any integer at any position in `arr`. For example, if `arr = [1,4,1,2]`, you can add `3` in the middle and make it `[1,4,3,1,2]`. Note that you can insert the integer at the very beginning or end of the array. Return _the **minimum** number of operations needed to make_ `target` _a **subsequence** of_ `arr`_._ A **subsequence** of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, `[2,7,4]` is a subsequence of `[4,2,3,7,2,1,4]` (the underlined elements), while `[2,4,2]` is not. **Example 1:** **Input:** target = \[5,1,3\], `arr` = \[9,4,2,3,4\] **Output:** 2 **Explanation:** You can add 5 and 1 in such a way that makes `arr` = \[5,9,4,1,2,3,4\], then target will be a subsequence of `arr`. **Example 2:** **Input:** target = \[6,4,8,1,3,2\], `arr` = \[4,7,6,2,3,8,6,1\] **Output:** 3 **Constraints:** * `1 <= target.length, arr.length <= 105` * `1 <= target[i], arr[i] <= 109` * `target` contains no duplicates.
Because the vector is sparse, use a data structure that stores the index and value where the element is nonzero.
✔ Python3 Solution | LIS
minimum-operations-to-make-a-subsequence
0
1
```\nclass Solution:\n def minOperations(self, target, arr):\n n, nums = len(target), []\n D = {target[i]: i for i in range(n)}\n res = [D[i] for i in arr if i in D.keys()]\n for i in res:\n j = bisect.bisect_left(nums, i)\n if j == len(nums): nums.append(i)\n else: nums[j] = i\n return n - len(nums)\n```
1
A **pangram** is a sentence where every letter of the English alphabet appears at least once. Given a string `sentence` containing only lowercase English letters, return `true` _if_ `sentence` _is a **pangram**, or_ `false` _otherwise._ **Example 1:** **Input:** sentence = "thequickbrownfoxjumpsoverthelazydog " **Output:** true **Explanation:** sentence contains at least one of every letter of the English alphabet. **Example 2:** **Input:** sentence = "leetcode " **Output:** false **Constraints:** * `1 <= sentence.length <= 1000` * `sentence` consists of lowercase English letters.
The problem can be reduced to computing Longest Common Subsequence between both arrays. Since one of the arrays has distinct elements, we can consider that these elements describe an arrangement of numbers, and we can replace each element in the other array with the index it appeared at in the first array. Then the problem is converted to finding Longest Increasing Subsequence in the second array, which can be done in O(n log n).
Python 3 || 6 lines, dct and bisect, w/ example || T/M: 96%/96%
minimum-operations-to-make-a-subsequence
0
1
\n```\nclass Solution:\n def minOperations(self, target: List[int], arr: List[int]) -> int:\n # Example: target = [6,4,8,1,3,2]\n dct, lst = {t: i for i,t in enumerate(target)}, [-1] # arr = [4,7,6,2,3,8,6,1]\n # \n for a in arr: # dct: {6:0, 4:1, 8:2, 1:3, 3:4, 2:5} \n if a in dct: # \n # a dct[a] lst \n if dct[a] > lst[-1]: lst.append(dct[a]) # \u2013\u2013\u2013\u2013\u2013 \u2013\u2013\u2013\u2013\u2013 \u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\n # 4 1 [-1, 1]\n else: lst[bisect_left(lst, dct[a])] = dct[a] # 7 [-1, 1]\n # 6 0 [-1, 0]\n return 1+len(target)-len(lst) # 2 5 [-1, 0, 5]\n # 3 [-1, 0, 4]\n # 8 2 [-1, 0, 2]\n # 6 [-1, 0, 2]\n # 1 3 [-1, 0, 2, 3]\n\n # return 1+(6)-(4) = 3\n\n```\n[https://leetcode.com/problems/minimum-operations-to-make-a-subsequence/submissions/888235439/](http://)\n\n\nI could be wrong, but I think that time complexity is *O*(*N*log*N*) and space complexity is *O*(*N*).
5
You are given an array `target` that consists of **distinct** integers and another integer array `arr` that **can** have duplicates. In one operation, you can insert any integer at any position in `arr`. For example, if `arr = [1,4,1,2]`, you can add `3` in the middle and make it `[1,4,3,1,2]`. Note that you can insert the integer at the very beginning or end of the array. Return _the **minimum** number of operations needed to make_ `target` _a **subsequence** of_ `arr`_._ A **subsequence** of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, `[2,7,4]` is a subsequence of `[4,2,3,7,2,1,4]` (the underlined elements), while `[2,4,2]` is not. **Example 1:** **Input:** target = \[5,1,3\], `arr` = \[9,4,2,3,4\] **Output:** 2 **Explanation:** You can add 5 and 1 in such a way that makes `arr` = \[5,9,4,1,2,3,4\], then target will be a subsequence of `arr`. **Example 2:** **Input:** target = \[6,4,8,1,3,2\], `arr` = \[4,7,6,2,3,8,6,1\] **Output:** 3 **Constraints:** * `1 <= target.length, arr.length <= 105` * `1 <= target[i], arr[i] <= 109` * `target` contains no duplicates.
Because the vector is sparse, use a data structure that stores the index and value where the element is nonzero.
Python 3 || 6 lines, dct and bisect, w/ example || T/M: 96%/96%
minimum-operations-to-make-a-subsequence
0
1
\n```\nclass Solution:\n def minOperations(self, target: List[int], arr: List[int]) -> int:\n # Example: target = [6,4,8,1,3,2]\n dct, lst = {t: i for i,t in enumerate(target)}, [-1] # arr = [4,7,6,2,3,8,6,1]\n # \n for a in arr: # dct: {6:0, 4:1, 8:2, 1:3, 3:4, 2:5} \n if a in dct: # \n # a dct[a] lst \n if dct[a] > lst[-1]: lst.append(dct[a]) # \u2013\u2013\u2013\u2013\u2013 \u2013\u2013\u2013\u2013\u2013 \u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\n # 4 1 [-1, 1]\n else: lst[bisect_left(lst, dct[a])] = dct[a] # 7 [-1, 1]\n # 6 0 [-1, 0]\n return 1+len(target)-len(lst) # 2 5 [-1, 0, 5]\n # 3 [-1, 0, 4]\n # 8 2 [-1, 0, 2]\n # 6 [-1, 0, 2]\n # 1 3 [-1, 0, 2, 3]\n\n # return 1+(6)-(4) = 3\n\n```\n[https://leetcode.com/problems/minimum-operations-to-make-a-subsequence/submissions/888235439/](http://)\n\n\nI could be wrong, but I think that time complexity is *O*(*N*log*N*) and space complexity is *O*(*N*).
5
A **pangram** is a sentence where every letter of the English alphabet appears at least once. Given a string `sentence` containing only lowercase English letters, return `true` _if_ `sentence` _is a **pangram**, or_ `false` _otherwise._ **Example 1:** **Input:** sentence = "thequickbrownfoxjumpsoverthelazydog " **Output:** true **Explanation:** sentence contains at least one of every letter of the English alphabet. **Example 2:** **Input:** sentence = "leetcode " **Output:** false **Constraints:** * `1 <= sentence.length <= 1000` * `sentence` consists of lowercase English letters.
The problem can be reduced to computing Longest Common Subsequence between both arrays. Since one of the arrays has distinct elements, we can consider that these elements describe an arrangement of numbers, and we can replace each element in the other array with the index it appeared at in the first array. Then the problem is converted to finding Longest Increasing Subsequence in the second array, which can be done in O(n log n).
[Python3] binary search
minimum-operations-to-make-a-subsequence
0
1
**Algo**\nMaintain an increasing array of indices of values in `target`. \n\n**Implementation** \n```\nclass Solution:\n def minOperations(self, target: List[int], arr: List[int]) -> int:\n loc = {x: i for i, x in enumerate(target)}\n stack = []\n for x in arr: \n if x in loc: \n i = bisect_left(stack, loc[x])\n if i < len(stack): stack[i] = loc[x]\n else: stack.append(loc[x])\n return len(target) - len(stack)\n```\n\n**Analysis**\nTime complexity `O(NlogN)`\nSpace complexity `O(N)`
5
You are given an array `target` that consists of **distinct** integers and another integer array `arr` that **can** have duplicates. In one operation, you can insert any integer at any position in `arr`. For example, if `arr = [1,4,1,2]`, you can add `3` in the middle and make it `[1,4,3,1,2]`. Note that you can insert the integer at the very beginning or end of the array. Return _the **minimum** number of operations needed to make_ `target` _a **subsequence** of_ `arr`_._ A **subsequence** of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, `[2,7,4]` is a subsequence of `[4,2,3,7,2,1,4]` (the underlined elements), while `[2,4,2]` is not. **Example 1:** **Input:** target = \[5,1,3\], `arr` = \[9,4,2,3,4\] **Output:** 2 **Explanation:** You can add 5 and 1 in such a way that makes `arr` = \[5,9,4,1,2,3,4\], then target will be a subsequence of `arr`. **Example 2:** **Input:** target = \[6,4,8,1,3,2\], `arr` = \[4,7,6,2,3,8,6,1\] **Output:** 3 **Constraints:** * `1 <= target.length, arr.length <= 105` * `1 <= target[i], arr[i] <= 109` * `target` contains no duplicates.
Because the vector is sparse, use a data structure that stores the index and value where the element is nonzero.
[Python3] binary search
minimum-operations-to-make-a-subsequence
0
1
**Algo**\nMaintain an increasing array of indices of values in `target`. \n\n**Implementation** \n```\nclass Solution:\n def minOperations(self, target: List[int], arr: List[int]) -> int:\n loc = {x: i for i, x in enumerate(target)}\n stack = []\n for x in arr: \n if x in loc: \n i = bisect_left(stack, loc[x])\n if i < len(stack): stack[i] = loc[x]\n else: stack.append(loc[x])\n return len(target) - len(stack)\n```\n\n**Analysis**\nTime complexity `O(NlogN)`\nSpace complexity `O(N)`
5
A **pangram** is a sentence where every letter of the English alphabet appears at least once. Given a string `sentence` containing only lowercase English letters, return `true` _if_ `sentence` _is a **pangram**, or_ `false` _otherwise._ **Example 1:** **Input:** sentence = "thequickbrownfoxjumpsoverthelazydog " **Output:** true **Explanation:** sentence contains at least one of every letter of the English alphabet. **Example 2:** **Input:** sentence = "leetcode " **Output:** false **Constraints:** * `1 <= sentence.length <= 1000` * `sentence` consists of lowercase English letters.
The problem can be reduced to computing Longest Common Subsequence between both arrays. Since one of the arrays has distinct elements, we can consider that these elements describe an arrangement of numbers, and we can replace each element in the other array with the index it appeared at in the first array. Then the problem is converted to finding Longest Increasing Subsequence in the second array, which can be done in O(n log n).
LCS - Russian Doll Approach with dict 100%
minimum-operations-to-make-a-subsequence
0
1
# Intuition \nBasically a variation of LCS(longest common subsequence), even simpler as target items are uniqle.\nSo dict can be used to get index of items in target, and making searching in arr even faster.\n\nGet all the [item]:index in target, search if each item in arr is also in target and make a list(loc) of index in target for this item.\neg: \ntarget:[5, 1, 3]\narr:[2, 3, 4, 5, 1, 2, 3, 5]\n----->loc: [2, 0, 1, 2, 0]\n\nGet LIS of loc, LIS(longest increasing subsequence) here is the LCS between arr and target.\n\nreturn len(target) - len(lcs)\n\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minOperations(self, target: List[int], arr: List[int]) -> int:\n d = defaultdict(int) \n \n loc = []\n lcs = []\n\n for i, j in enumerate(target):\n d[j] = i\n \n\n\n\n for i in arr:\n if i in d.keys():\n #print(i)\n loc.append(d[i])\n \n for i in loc:\n tmp = bisect.bisect_left(lcs, i)\n if tmp == len(lcs):\n lcs.append(i)\n else:\n lcs[tmp] = i\n\n \n\n return len(target) - len(lcs)\n```
0
You are given an array `target` that consists of **distinct** integers and another integer array `arr` that **can** have duplicates. In one operation, you can insert any integer at any position in `arr`. For example, if `arr = [1,4,1,2]`, you can add `3` in the middle and make it `[1,4,3,1,2]`. Note that you can insert the integer at the very beginning or end of the array. Return _the **minimum** number of operations needed to make_ `target` _a **subsequence** of_ `arr`_._ A **subsequence** of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, `[2,7,4]` is a subsequence of `[4,2,3,7,2,1,4]` (the underlined elements), while `[2,4,2]` is not. **Example 1:** **Input:** target = \[5,1,3\], `arr` = \[9,4,2,3,4\] **Output:** 2 **Explanation:** You can add 5 and 1 in such a way that makes `arr` = \[5,9,4,1,2,3,4\], then target will be a subsequence of `arr`. **Example 2:** **Input:** target = \[6,4,8,1,3,2\], `arr` = \[4,7,6,2,3,8,6,1\] **Output:** 3 **Constraints:** * `1 <= target.length, arr.length <= 105` * `1 <= target[i], arr[i] <= 109` * `target` contains no duplicates.
Because the vector is sparse, use a data structure that stores the index and value where the element is nonzero.
LCS - Russian Doll Approach with dict 100%
minimum-operations-to-make-a-subsequence
0
1
# Intuition \nBasically a variation of LCS(longest common subsequence), even simpler as target items are uniqle.\nSo dict can be used to get index of items in target, and making searching in arr even faster.\n\nGet all the [item]:index in target, search if each item in arr is also in target and make a list(loc) of index in target for this item.\neg: \ntarget:[5, 1, 3]\narr:[2, 3, 4, 5, 1, 2, 3, 5]\n----->loc: [2, 0, 1, 2, 0]\n\nGet LIS of loc, LIS(longest increasing subsequence) here is the LCS between arr and target.\n\nreturn len(target) - len(lcs)\n\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minOperations(self, target: List[int], arr: List[int]) -> int:\n d = defaultdict(int) \n \n loc = []\n lcs = []\n\n for i, j in enumerate(target):\n d[j] = i\n \n\n\n\n for i in arr:\n if i in d.keys():\n #print(i)\n loc.append(d[i])\n \n for i in loc:\n tmp = bisect.bisect_left(lcs, i)\n if tmp == len(lcs):\n lcs.append(i)\n else:\n lcs[tmp] = i\n\n \n\n return len(target) - len(lcs)\n```
0
A **pangram** is a sentence where every letter of the English alphabet appears at least once. Given a string `sentence` containing only lowercase English letters, return `true` _if_ `sentence` _is a **pangram**, or_ `false` _otherwise._ **Example 1:** **Input:** sentence = "thequickbrownfoxjumpsoverthelazydog " **Output:** true **Explanation:** sentence contains at least one of every letter of the English alphabet. **Example 2:** **Input:** sentence = "leetcode " **Output:** false **Constraints:** * `1 <= sentence.length <= 1000` * `sentence` consists of lowercase English letters.
The problem can be reduced to computing Longest Common Subsequence between both arrays. Since one of the arrays has distinct elements, we can consider that these elements describe an arrangement of numbers, and we can replace each element in the other array with the index it appeared at in the first array. Then the problem is converted to finding Longest Increasing Subsequence in the second array, which can be done in O(n log n).
Python |DP vs Bisect | Short clean code
minimum-operations-to-make-a-subsequence
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTwo solutions are presented: DP $O(N^2)$ (TLE) and Bisect $O(NlogN)$\nThe DP solution works for any kind of target array; it doesn\'t use the condition: the numbers in the target array are distinct.\n\nThe Bisect solution, by using the distinct condition, for each element in the target array, we consider their unique position in it.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nDP $O(N^2)$ (TLE) \nBisect $O(NlogN)$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nDP $O(N^2)$ (MLE)\nBisect $O(N)$\n\n# Code DP Solution\n```\nclass Solution:\n def minOperations(self, target: List[int], arr: List[int]) -> int:\n\n nt, na = len(target), len(arr)\n dp = [[0 for t in range(nt + 1)] for a in range(na + 1)]\n\n for a in range(na - 1, -1, -1):\n if(arr[a] == target[nt - 1]):\n break\n else:\n dp[a][nt - 1] = 1\n isMatch = False\n for t in range(nt - 1, -1, -1):\n if(arr[na - 1] == target[t]):\n isMatch = True\n dp[na - 1][t] = nt - t - 1 if isMatch else nt - t \n \n for t in range(nt - 2, -1, -1):\n for a in range(na - 2, -1, -1):\n if(target[t] == arr[a]):\n dp[a][t] = dp[a + 1][t + 1]\n else:\n dp[a][t] = min(dp[a + 1][t], 1 + dp[a][t + 1])\n return dp[0][0]\n```\n\n# Code Bisect Solution\n```\nimport bisect\nclass Solution:\n def minOperations(self, target: List[int], arr: List[int]) -> int:\n nt, na = len(target), len(arr)\n dictT = {target[t]: t for t in range(nt)}\n backList = [-1]\n for a in range(na):\n if arr[a] in dictT:\n if(backList[-1] < dictT[arr[a]]):\n backList.append(dictT[arr[a]])\n else:\n backList[bisect.bisect_left(backList, dictT[arr[a]])] = dictT[arr[a]]\n return nt - len(backList) + 1\n```
0
You are given an array `target` that consists of **distinct** integers and another integer array `arr` that **can** have duplicates. In one operation, you can insert any integer at any position in `arr`. For example, if `arr = [1,4,1,2]`, you can add `3` in the middle and make it `[1,4,3,1,2]`. Note that you can insert the integer at the very beginning or end of the array. Return _the **minimum** number of operations needed to make_ `target` _a **subsequence** of_ `arr`_._ A **subsequence** of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, `[2,7,4]` is a subsequence of `[4,2,3,7,2,1,4]` (the underlined elements), while `[2,4,2]` is not. **Example 1:** **Input:** target = \[5,1,3\], `arr` = \[9,4,2,3,4\] **Output:** 2 **Explanation:** You can add 5 and 1 in such a way that makes `arr` = \[5,9,4,1,2,3,4\], then target will be a subsequence of `arr`. **Example 2:** **Input:** target = \[6,4,8,1,3,2\], `arr` = \[4,7,6,2,3,8,6,1\] **Output:** 3 **Constraints:** * `1 <= target.length, arr.length <= 105` * `1 <= target[i], arr[i] <= 109` * `target` contains no duplicates.
Because the vector is sparse, use a data structure that stores the index and value where the element is nonzero.
Python |DP vs Bisect | Short clean code
minimum-operations-to-make-a-subsequence
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTwo solutions are presented: DP $O(N^2)$ (TLE) and Bisect $O(NlogN)$\nThe DP solution works for any kind of target array; it doesn\'t use the condition: the numbers in the target array are distinct.\n\nThe Bisect solution, by using the distinct condition, for each element in the target array, we consider their unique position in it.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nDP $O(N^2)$ (TLE) \nBisect $O(NlogN)$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nDP $O(N^2)$ (MLE)\nBisect $O(N)$\n\n# Code DP Solution\n```\nclass Solution:\n def minOperations(self, target: List[int], arr: List[int]) -> int:\n\n nt, na = len(target), len(arr)\n dp = [[0 for t in range(nt + 1)] for a in range(na + 1)]\n\n for a in range(na - 1, -1, -1):\n if(arr[a] == target[nt - 1]):\n break\n else:\n dp[a][nt - 1] = 1\n isMatch = False\n for t in range(nt - 1, -1, -1):\n if(arr[na - 1] == target[t]):\n isMatch = True\n dp[na - 1][t] = nt - t - 1 if isMatch else nt - t \n \n for t in range(nt - 2, -1, -1):\n for a in range(na - 2, -1, -1):\n if(target[t] == arr[a]):\n dp[a][t] = dp[a + 1][t + 1]\n else:\n dp[a][t] = min(dp[a + 1][t], 1 + dp[a][t + 1])\n return dp[0][0]\n```\n\n# Code Bisect Solution\n```\nimport bisect\nclass Solution:\n def minOperations(self, target: List[int], arr: List[int]) -> int:\n nt, na = len(target), len(arr)\n dictT = {target[t]: t for t in range(nt)}\n backList = [-1]\n for a in range(na):\n if arr[a] in dictT:\n if(backList[-1] < dictT[arr[a]]):\n backList.append(dictT[arr[a]])\n else:\n backList[bisect.bisect_left(backList, dictT[arr[a]])] = dictT[arr[a]]\n return nt - len(backList) + 1\n```
0
A **pangram** is a sentence where every letter of the English alphabet appears at least once. Given a string `sentence` containing only lowercase English letters, return `true` _if_ `sentence` _is a **pangram**, or_ `false` _otherwise._ **Example 1:** **Input:** sentence = "thequickbrownfoxjumpsoverthelazydog " **Output:** true **Explanation:** sentence contains at least one of every letter of the English alphabet. **Example 2:** **Input:** sentence = "leetcode " **Output:** false **Constraints:** * `1 <= sentence.length <= 1000` * `sentence` consists of lowercase English letters.
The problem can be reduced to computing Longest Common Subsequence between both arrays. Since one of the arrays has distinct elements, we can consider that these elements describe an arrangement of numbers, and we can replace each element in the other array with the index it appeared at in the first array. Then the problem is converted to finding Longest Increasing Subsequence in the second array, which can be done in O(n log n).
Python (Simple Binary Search)
minimum-operations-to-make-a-subsequence
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minOperations(self, target, arr):\n dict1 = {j:i for i,j in enumerate(target)}\n\n stack = []\n\n for i in arr:\n if i in dict1:\n stack.append(dict1[i])\n\n return len(target) - self.dfs(stack)\n\n def dfs(self, nums):\n ans = []\n\n for i in nums:\n idx = bisect.bisect_left(ans,i)\n\n if idx == len(ans):\n ans.append(i)\n else:\n ans[idx] = i\n\n return len(ans)\n\n\n\n\n\n\n\n\n\n \n\n\n\n\n \n\n\n\n\n\n\n\n\n\n\n \n```
0
You are given an array `target` that consists of **distinct** integers and another integer array `arr` that **can** have duplicates. In one operation, you can insert any integer at any position in `arr`. For example, if `arr = [1,4,1,2]`, you can add `3` in the middle and make it `[1,4,3,1,2]`. Note that you can insert the integer at the very beginning or end of the array. Return _the **minimum** number of operations needed to make_ `target` _a **subsequence** of_ `arr`_._ A **subsequence** of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, `[2,7,4]` is a subsequence of `[4,2,3,7,2,1,4]` (the underlined elements), while `[2,4,2]` is not. **Example 1:** **Input:** target = \[5,1,3\], `arr` = \[9,4,2,3,4\] **Output:** 2 **Explanation:** You can add 5 and 1 in such a way that makes `arr` = \[5,9,4,1,2,3,4\], then target will be a subsequence of `arr`. **Example 2:** **Input:** target = \[6,4,8,1,3,2\], `arr` = \[4,7,6,2,3,8,6,1\] **Output:** 3 **Constraints:** * `1 <= target.length, arr.length <= 105` * `1 <= target[i], arr[i] <= 109` * `target` contains no duplicates.
Because the vector is sparse, use a data structure that stores the index and value where the element is nonzero.
Python (Simple Binary Search)
minimum-operations-to-make-a-subsequence
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minOperations(self, target, arr):\n dict1 = {j:i for i,j in enumerate(target)}\n\n stack = []\n\n for i in arr:\n if i in dict1:\n stack.append(dict1[i])\n\n return len(target) - self.dfs(stack)\n\n def dfs(self, nums):\n ans = []\n\n for i in nums:\n idx = bisect.bisect_left(ans,i)\n\n if idx == len(ans):\n ans.append(i)\n else:\n ans[idx] = i\n\n return len(ans)\n\n\n\n\n\n\n\n\n\n \n\n\n\n\n \n\n\n\n\n\n\n\n\n\n\n \n```
0
A **pangram** is a sentence where every letter of the English alphabet appears at least once. Given a string `sentence` containing only lowercase English letters, return `true` _if_ `sentence` _is a **pangram**, or_ `false` _otherwise._ **Example 1:** **Input:** sentence = "thequickbrownfoxjumpsoverthelazydog " **Output:** true **Explanation:** sentence contains at least one of every letter of the English alphabet. **Example 2:** **Input:** sentence = "leetcode " **Output:** false **Constraints:** * `1 <= sentence.length <= 1000` * `sentence` consists of lowercase English letters.
The problem can be reduced to computing Longest Common Subsequence between both arrays. Since one of the arrays has distinct elements, we can consider that these elements describe an arrangement of numbers, and we can replace each element in the other array with the index it appeared at in the first array. Then the problem is converted to finding Longest Increasing Subsequence in the second array, which can be done in O(n log n).
Python easy to read and understand | lcs-lis
minimum-operations-to-make-a-subsequence
0
1
**LCS(TLE):**\n```\nclass Solution:\n def lcs(self, nums1, nums2, m, n):\n if m == 0 or n == 0:\n return 0\n if (m, n) in self.d:\n return self.d[(m, n)]\n if nums1[m-1] == nums2[n-1]:\n self.d[(m, n)] = self.lcs(nums1, nums2, m-1, n-1) + 1\n return self.d[(m, n)]\n else:\n self.d[(m, n)] = max(self.lcs(nums1, nums2, m, n-1), self.lcs(nums1, nums2, m-1, n))\n return self.d[(m, n)]\n \n def minOperations(self, target: List[int], arr: List[int]) -> int:\n self.d = {}\n m, n = len(target), len(arr)\n return m - self.lcs(target, arr, m, n)\n```\n**LIS(accepted):**\n```\nclass Solution:\n def lislength(self, nums):\n lis = [nums[0]]\n for num in nums[1:]:\n if num > lis[-1]:\n lis.append(num)\n else:\n index = bisect_left(lis, num)\n lis[index] = num\n return len(lis)\n \n def minOperations(self, target: List[int], arr: List[int]) -> int:\n d = {num: i for i, num in enumerate(target)}\n nums = []\n for val in arr:\n if val in d:\n nums.append(d[val])\n \n if not nums:\n return len(target)\n return len(target) - self.lislength(nums)\n```
0
You are given an array `target` that consists of **distinct** integers and another integer array `arr` that **can** have duplicates. In one operation, you can insert any integer at any position in `arr`. For example, if `arr = [1,4,1,2]`, you can add `3` in the middle and make it `[1,4,3,1,2]`. Note that you can insert the integer at the very beginning or end of the array. Return _the **minimum** number of operations needed to make_ `target` _a **subsequence** of_ `arr`_._ A **subsequence** of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, `[2,7,4]` is a subsequence of `[4,2,3,7,2,1,4]` (the underlined elements), while `[2,4,2]` is not. **Example 1:** **Input:** target = \[5,1,3\], `arr` = \[9,4,2,3,4\] **Output:** 2 **Explanation:** You can add 5 and 1 in such a way that makes `arr` = \[5,9,4,1,2,3,4\], then target will be a subsequence of `arr`. **Example 2:** **Input:** target = \[6,4,8,1,3,2\], `arr` = \[4,7,6,2,3,8,6,1\] **Output:** 3 **Constraints:** * `1 <= target.length, arr.length <= 105` * `1 <= target[i], arr[i] <= 109` * `target` contains no duplicates.
Because the vector is sparse, use a data structure that stores the index and value where the element is nonzero.
Python easy to read and understand | lcs-lis
minimum-operations-to-make-a-subsequence
0
1
**LCS(TLE):**\n```\nclass Solution:\n def lcs(self, nums1, nums2, m, n):\n if m == 0 or n == 0:\n return 0\n if (m, n) in self.d:\n return self.d[(m, n)]\n if nums1[m-1] == nums2[n-1]:\n self.d[(m, n)] = self.lcs(nums1, nums2, m-1, n-1) + 1\n return self.d[(m, n)]\n else:\n self.d[(m, n)] = max(self.lcs(nums1, nums2, m, n-1), self.lcs(nums1, nums2, m-1, n))\n return self.d[(m, n)]\n \n def minOperations(self, target: List[int], arr: List[int]) -> int:\n self.d = {}\n m, n = len(target), len(arr)\n return m - self.lcs(target, arr, m, n)\n```\n**LIS(accepted):**\n```\nclass Solution:\n def lislength(self, nums):\n lis = [nums[0]]\n for num in nums[1:]:\n if num > lis[-1]:\n lis.append(num)\n else:\n index = bisect_left(lis, num)\n lis[index] = num\n return len(lis)\n \n def minOperations(self, target: List[int], arr: List[int]) -> int:\n d = {num: i for i, num in enumerate(target)}\n nums = []\n for val in arr:\n if val in d:\n nums.append(d[val])\n \n if not nums:\n return len(target)\n return len(target) - self.lislength(nums)\n```
0
A **pangram** is a sentence where every letter of the English alphabet appears at least once. Given a string `sentence` containing only lowercase English letters, return `true` _if_ `sentence` _is a **pangram**, or_ `false` _otherwise._ **Example 1:** **Input:** sentence = "thequickbrownfoxjumpsoverthelazydog " **Output:** true **Explanation:** sentence contains at least one of every letter of the English alphabet. **Example 2:** **Input:** sentence = "leetcode " **Output:** false **Constraints:** * `1 <= sentence.length <= 1000` * `sentence` consists of lowercase English letters.
The problem can be reduced to computing Longest Common Subsequence between both arrays. Since one of the arrays has distinct elements, we can consider that these elements describe an arrangement of numbers, and we can replace each element in the other array with the index it appeared at in the first array. Then the problem is converted to finding Longest Increasing Subsequence in the second array, which can be done in O(n log n).
Python LIS with SortedList
minimum-operations-to-make-a-subsequence
0
1
# Intuition\nBasically we are looking for the longest subsequence of `target` that can be found within `arr`. Since we\'re told that `target` has unique values, we can consider the index within `target` of each value in `arr`, and then solve the longest increasing subsequence problem.\n\nOnce we know the length of the LIS, we know how many characters would need to be added to `arr` in order for `arr` to contain all of `target` as one of its subsequences.\n\n# Approach\nUse a `dict` mapping of $$value \\to index$$ for the values at each index of target.\nUse `sortedcontainers.SortedList` to build a monotonic list of increasing values that are collected during the $$LIS$$ algorithm.\n\nFor each value in `arr`, lookup the position $$pos$$ of that same value in `target`. If not found, skip this value. Find the index in the monotonic list, of the first $$pos_2$$ that is greater or equal to $$pos$$, and replace that value with $$pos$$. If $$pos$$ is the highest value encountered so far, simply append it to the monotonic list.\n\nThe answer is `len(target) - len(monotonic list)`.\n\n# Complexity\n### Time complexity:\n\n$$O(n*log(m))$$. \nEach iteration is $$O(log(m))$$ for bisecting and modifying the list, which could be as long as $$m$$. Building the lookup table for `target` positions costs $$O(n)$$.\n\n \n\n### Space complexity:\n$$O(m*log(m))$$ for the two objects created, the target position lookup and the `SortedList`.\n\n# Code\n```\nfrom sortedcontainers import SortedList\n\n\nclass Solution:\n\n def minOperations(self, target: List[int], arr: List[int]) -> int:\n target_pos = {val:i for i,val in enumerate(target)}\n mono = SortedList()\n for pos in (target_pos[i] for i in arr if i in target_pos):\n idx = mono.bisect_left(pos)\n if idx < len(mono):\n if pos == mono[idx]:\n continue\n del mono[idx]\n mono.add(pos)\n return len(target) - len(mono)\n\n```
0
You are given an array `target` that consists of **distinct** integers and another integer array `arr` that **can** have duplicates. In one operation, you can insert any integer at any position in `arr`. For example, if `arr = [1,4,1,2]`, you can add `3` in the middle and make it `[1,4,3,1,2]`. Note that you can insert the integer at the very beginning or end of the array. Return _the **minimum** number of operations needed to make_ `target` _a **subsequence** of_ `arr`_._ A **subsequence** of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, `[2,7,4]` is a subsequence of `[4,2,3,7,2,1,4]` (the underlined elements), while `[2,4,2]` is not. **Example 1:** **Input:** target = \[5,1,3\], `arr` = \[9,4,2,3,4\] **Output:** 2 **Explanation:** You can add 5 and 1 in such a way that makes `arr` = \[5,9,4,1,2,3,4\], then target will be a subsequence of `arr`. **Example 2:** **Input:** target = \[6,4,8,1,3,2\], `arr` = \[4,7,6,2,3,8,6,1\] **Output:** 3 **Constraints:** * `1 <= target.length, arr.length <= 105` * `1 <= target[i], arr[i] <= 109` * `target` contains no duplicates.
Because the vector is sparse, use a data structure that stores the index and value where the element is nonzero.
Python LIS with SortedList
minimum-operations-to-make-a-subsequence
0
1
# Intuition\nBasically we are looking for the longest subsequence of `target` that can be found within `arr`. Since we\'re told that `target` has unique values, we can consider the index within `target` of each value in `arr`, and then solve the longest increasing subsequence problem.\n\nOnce we know the length of the LIS, we know how many characters would need to be added to `arr` in order for `arr` to contain all of `target` as one of its subsequences.\n\n# Approach\nUse a `dict` mapping of $$value \\to index$$ for the values at each index of target.\nUse `sortedcontainers.SortedList` to build a monotonic list of increasing values that are collected during the $$LIS$$ algorithm.\n\nFor each value in `arr`, lookup the position $$pos$$ of that same value in `target`. If not found, skip this value. Find the index in the monotonic list, of the first $$pos_2$$ that is greater or equal to $$pos$$, and replace that value with $$pos$$. If $$pos$$ is the highest value encountered so far, simply append it to the monotonic list.\n\nThe answer is `len(target) - len(monotonic list)`.\n\n# Complexity\n### Time complexity:\n\n$$O(n*log(m))$$. \nEach iteration is $$O(log(m))$$ for bisecting and modifying the list, which could be as long as $$m$$. Building the lookup table for `target` positions costs $$O(n)$$.\n\n \n\n### Space complexity:\n$$O(m*log(m))$$ for the two objects created, the target position lookup and the `SortedList`.\n\n# Code\n```\nfrom sortedcontainers import SortedList\n\n\nclass Solution:\n\n def minOperations(self, target: List[int], arr: List[int]) -> int:\n target_pos = {val:i for i,val in enumerate(target)}\n mono = SortedList()\n for pos in (target_pos[i] for i in arr if i in target_pos):\n idx = mono.bisect_left(pos)\n if idx < len(mono):\n if pos == mono[idx]:\n continue\n del mono[idx]\n mono.add(pos)\n return len(target) - len(mono)\n\n```
0
A **pangram** is a sentence where every letter of the English alphabet appears at least once. Given a string `sentence` containing only lowercase English letters, return `true` _if_ `sentence` _is a **pangram**, or_ `false` _otherwise._ **Example 1:** **Input:** sentence = "thequickbrownfoxjumpsoverthelazydog " **Output:** true **Explanation:** sentence contains at least one of every letter of the English alphabet. **Example 2:** **Input:** sentence = "leetcode " **Output:** false **Constraints:** * `1 <= sentence.length <= 1000` * `sentence` consists of lowercase English letters.
The problem can be reduced to computing Longest Common Subsequence between both arrays. Since one of the arrays has distinct elements, we can consider that these elements describe an arrangement of numbers, and we can replace each element in the other array with the index it appeared at in the first array. Then the problem is converted to finding Longest Increasing Subsequence in the second array, which can be done in O(n log n).
🚀✅ Beats 100% , Simple Maths
calculate-money-in-leetcode-bank
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCalculate the Saving from each Week and observe a pattern between them\n```\nWeek 1 -> {1,2,3,4,5,6,7} = 28\nWeek 2 -> {2,3,4,5,6,7,8} = 28 + 7\nand so on\n```\nEach week the Saving increases by an amount of 7\n\n---\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n1. The solve function calculates the total savings for complete weeks. It uses a loop to iterate through each week and adds the corresponding savings. The savings for each week follow an arithmetic sequence, starting with $28 (for Monday of the first week) and increasing by 7 for each subsequent week.\n2. In the totalMoney function, the number of complete weeks is calculated by dividing n by 7. The solve function is then called to calculate the total savings for these complete weeks.\n3. The number of remaining days after complete weeks is calculated using the modulus operator (%).\n4. If there are no remaining days (day == 0), the function returns the total savings for complete weeks (ans).\n5. If there are remaining days, the code enters an else block. It initializes a variable week to week + 1 and enters a loop that runs for the number of remaining days. In each iteration, it adds the current value of week to ans and increments week.\n6. Finally, the function returns the total savings (ans).\n\nThis approach also calculates the total savings by considering both complete weeks and the remaining days\n# Complexity\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1) -> No Extra Space is being used\n\n---\n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int solve(int week){\n int result=0;\n for(int i=0;i<week;i++){\n result+=28+(i*7);\n }\n return result;\n }\n int totalMoney(int n) {\n int week=n/7;\n int ans=solve(week);\n int day=n%7;\n if(day==0){\n return ans;\n }\n else{\n week++;\n while(day--){\n ans+=week++;\n }\n }\n return ans;\n }\n};\n```\n```Javascript []\nclass Solution {\n solve(week) {\n let result = 0;\n for (let i = 0; i < week; i++) {\n result += 28 + (i * 7);\n }\n return result;\n }\n\n totalMoney(n) {\n const week = Math.floor(n / 7);\n let ans = this.solve(week);\n const day = n % 7;\n if (day === 0) {\n return ans;\n } else {\n let currentWeek = week + 1;\n while (day--) {\n ans += currentWeek++;\n }\n }\n return ans;\n }\n}\n```\n```Python []\nclass Solution:\n def solve(self, week):\n result = 0\n for i in range(week):\n result += 28 + (i * 7)\n return result\n\n def totalMoney(self, n):\n week = n // 7\n ans = self.solve(week)\n day = n % 7\n if day == 0:\n return ans\n else:\n current_week = week + 1\n while day > 0:\n ans += current_week\n current_week += 1\n day -= 1\n return ans\n```\n```Java []\npublic class Solution {\n public int solve(int week) {\n int result = 0;\n for (int i = 0; i < week; i++) {\n result += 28 + (i * 7);\n }\n return result;\n }\n\n public int totalMoney(int n) {\n int week = n / 7;\n int ans = solve(week);\n int day = n % 7;\n if (day == 0) {\n return ans;\n } else {\n int currentWeek = week + 1;\n while (day > 0) {\n ans += currentWeek;\n currentWeek++;\n day--;\n }\n }\n return ans;\n }\n```\n
11
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**. He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put 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:** * `1 <= n <= 1000`
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
🚀✅ Beats 100% , Simple Maths
calculate-money-in-leetcode-bank
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCalculate the Saving from each Week and observe a pattern between them\n```\nWeek 1 -> {1,2,3,4,5,6,7} = 28\nWeek 2 -> {2,3,4,5,6,7,8} = 28 + 7\nand so on\n```\nEach week the Saving increases by an amount of 7\n\n---\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n1. The solve function calculates the total savings for complete weeks. It uses a loop to iterate through each week and adds the corresponding savings. The savings for each week follow an arithmetic sequence, starting with $28 (for Monday of the first week) and increasing by 7 for each subsequent week.\n2. In the totalMoney function, the number of complete weeks is calculated by dividing n by 7. The solve function is then called to calculate the total savings for these complete weeks.\n3. The number of remaining days after complete weeks is calculated using the modulus operator (%).\n4. If there are no remaining days (day == 0), the function returns the total savings for complete weeks (ans).\n5. If there are remaining days, the code enters an else block. It initializes a variable week to week + 1 and enters a loop that runs for the number of remaining days. In each iteration, it adds the current value of week to ans and increments week.\n6. Finally, the function returns the total savings (ans).\n\nThis approach also calculates the total savings by considering both complete weeks and the remaining days\n# Complexity\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1) -> No Extra Space is being used\n\n---\n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int solve(int week){\n int result=0;\n for(int i=0;i<week;i++){\n result+=28+(i*7);\n }\n return result;\n }\n int totalMoney(int n) {\n int week=n/7;\n int ans=solve(week);\n int day=n%7;\n if(day==0){\n return ans;\n }\n else{\n week++;\n while(day--){\n ans+=week++;\n }\n }\n return ans;\n }\n};\n```\n```Javascript []\nclass Solution {\n solve(week) {\n let result = 0;\n for (let i = 0; i < week; i++) {\n result += 28 + (i * 7);\n }\n return result;\n }\n\n totalMoney(n) {\n const week = Math.floor(n / 7);\n let ans = this.solve(week);\n const day = n % 7;\n if (day === 0) {\n return ans;\n } else {\n let currentWeek = week + 1;\n while (day--) {\n ans += currentWeek++;\n }\n }\n return ans;\n }\n}\n```\n```Python []\nclass Solution:\n def solve(self, week):\n result = 0\n for i in range(week):\n result += 28 + (i * 7)\n return result\n\n def totalMoney(self, n):\n week = n // 7\n ans = self.solve(week)\n day = n % 7\n if day == 0:\n return ans\n else:\n current_week = week + 1\n while day > 0:\n ans += current_week\n current_week += 1\n day -= 1\n return ans\n```\n```Java []\npublic class Solution {\n public int solve(int week) {\n int result = 0;\n for (int i = 0; i < week; i++) {\n result += 28 + (i * 7);\n }\n return result;\n }\n\n public int totalMoney(int n) {\n int week = n / 7;\n int ans = solve(week);\n int day = n % 7;\n if (day == 0) {\n return ans;\n } else {\n int currentWeek = week + 1;\n while (day > 0) {\n ans += currentWeek;\n currentWeek++;\n day--;\n }\n }\n return ans;\n }\n```\n
11
You are given the logs for users' actions on LeetCode, and an integer `k`. The logs are represented by a 2D integer array `logs` where each `logs[i] = [IDi, timei]` indicates that the user with `IDi` performed an action at the minute `timei`. **Multiple users** can perform actions simultaneously, and a single user can perform **multiple actions** in the same minute. The **user active minutes (UAM)** for a given user is defined as the **number of unique minutes** in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it. You are to calculate a **1-indexed** array `answer` of size `k` such that, for each `j` (`1 <= j <= k`), `answer[j]` is the **number of users** whose **UAM** equals `j`. Return _the array_ `answer` _as described above_. **Example 1:** **Input:** logs = \[\[0,5\],\[1,2\],\[0,2\],\[0,5\],\[1,3\]\], k = 5 **Output:** \[0,2,0,0,0\] **Explanation:** The user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once). The user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. Since both users have a UAM of 2, answer\[2\] is 2, and the remaining answer\[j\] values are 0. **Example 2:** **Input:** logs = \[\[1,1\],\[2,2\],\[2,3\]\], k = 4 **Output:** \[1,1,0,0\] **Explanation:** The user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1. The user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. There is one user with a UAM of 1 and one with a UAM of 2. Hence, answer\[1\] = 1, answer\[2\] = 1, and the remaining values are 0. **Constraints:** * `1 <= logs.length <= 104` * `0 <= IDi <= 109` * `1 <= timei <= 105` * `k` is in the range `[The maximum **UAM** for a user, 105]`.
Simulate the process by keeping track of how much money John is putting in and which day of the week it is, and use this information to deduce how much money John will put in the next day.
🥇 O (1) math explained ; ] ✅
calculate-money-in-leetcode-bank
1
1
\n**UPVOTE IF HELPFuuL**\n\n# Problem Statement\n- Start by `$1` on first day `[MONDAY]`.\n- For every day in the week put `$1` more than yesterday.\n- On next Monday, start again by increasing `$1` from previous Monday.\n\n# Approach\n```\nWeek 1 money : [1, 2, 3, 4, 5, 6, 7] -> 28\nWeek 2 money : [2, 3, 4, 5, 6, 7, 8] -> 28 + 7\nWeek 3 money : [3, 4, 5, 6, 7, 8, 9] -> 28 + 7 + 7\n```\nThis form an `Arithmetic Progression`\n\nNow `n = 7*w + extra_days`\nFor complete weeks [ w in code] :\n- AP starting with `28`, and increment of `7`.\n- Money for `w` complete weeks = `[ 28 * w ] + [ 0 + 7 + 14 + ... + 7w ]`\n`=[ 28w + 7w * (w - 1) / 2 ]`\n\nFor days that donot form a complete week :\n- Add money using loop starting with `w + 1` for x days that are left. `x<7`\n\n\n\n# Complexity\n- Time complexity: O ( 1 )\n\n- Space complexity: O ( 1 )\n\n\nThis solution can be reduced to few lines as it is basic math, but then code wouldnot be readable. Happy Coding!!\n``` C++ []\nclass Solution {\npublic:\n int totalMoney(int n) {\n int w = n / 7;\n int money = w * 28;\n money += (7 * w * (w - 1)) / 2;\n\n if (n % 7) {\n int extra_days = n % 7;\n int money_to_add = w + 1;\n for (int i = 0; i < extra_days; ++i) {\n money += money_to_add;\n money_to_add += 1;\n }\n }\n return money;\n }\n};\n\n```\n``` Python []\nclass Solution:\n def totalMoney(self, n: int) -> int:\n w = n // 7\n money = w * 28\n money += (7 * w *( w - 1))//2\n\n if (n % 7):\n extra_days = n % 7\n money_to_add = w + 1\n for i in range(extra_days):\n money += money_to_add\n money_to_add += 1\n\n return money\n```\n``` JAVA []\nclass Solution {\n public int totalMoney(int n) {\n int w = n / 7;\n int money = w * 28;\n money += (7 * w * (w - 1)) / 2;\n\n if (n % 7 != 0) {\n int extraDays = n % 7;\n int moneyToAdd = w + 1;\n for (int i = 0; i < extraDays; ++i) {\n money += moneyToAdd;\n moneyToAdd += 1;\n }\n }\n\n return money;\n }\n}\n```\n\n**UPVOTE IF HELPFuuL**\n\n![Screenshot 2023-12-05 at 6.18.22 AM.png](https://assets.leetcode.com/users/images/4fed8e49-27ed-40e3-a29b-4128bced273e_1701821876.0689087.png)\n
72
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**. He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put 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:** * `1 <= n <= 1000`
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
🥇 O (1) math explained ; ] ✅
calculate-money-in-leetcode-bank
1
1
\n**UPVOTE IF HELPFuuL**\n\n# Problem Statement\n- Start by `$1` on first day `[MONDAY]`.\n- For every day in the week put `$1` more than yesterday.\n- On next Monday, start again by increasing `$1` from previous Monday.\n\n# Approach\n```\nWeek 1 money : [1, 2, 3, 4, 5, 6, 7] -> 28\nWeek 2 money : [2, 3, 4, 5, 6, 7, 8] -> 28 + 7\nWeek 3 money : [3, 4, 5, 6, 7, 8, 9] -> 28 + 7 + 7\n```\nThis form an `Arithmetic Progression`\n\nNow `n = 7*w + extra_days`\nFor complete weeks [ w in code] :\n- AP starting with `28`, and increment of `7`.\n- Money for `w` complete weeks = `[ 28 * w ] + [ 0 + 7 + 14 + ... + 7w ]`\n`=[ 28w + 7w * (w - 1) / 2 ]`\n\nFor days that donot form a complete week :\n- Add money using loop starting with `w + 1` for x days that are left. `x<7`\n\n\n\n# Complexity\n- Time complexity: O ( 1 )\n\n- Space complexity: O ( 1 )\n\n\nThis solution can be reduced to few lines as it is basic math, but then code wouldnot be readable. Happy Coding!!\n``` C++ []\nclass Solution {\npublic:\n int totalMoney(int n) {\n int w = n / 7;\n int money = w * 28;\n money += (7 * w * (w - 1)) / 2;\n\n if (n % 7) {\n int extra_days = n % 7;\n int money_to_add = w + 1;\n for (int i = 0; i < extra_days; ++i) {\n money += money_to_add;\n money_to_add += 1;\n }\n }\n return money;\n }\n};\n\n```\n``` Python []\nclass Solution:\n def totalMoney(self, n: int) -> int:\n w = n // 7\n money = w * 28\n money += (7 * w *( w - 1))//2\n\n if (n % 7):\n extra_days = n % 7\n money_to_add = w + 1\n for i in range(extra_days):\n money += money_to_add\n money_to_add += 1\n\n return money\n```\n``` JAVA []\nclass Solution {\n public int totalMoney(int n) {\n int w = n / 7;\n int money = w * 28;\n money += (7 * w * (w - 1)) / 2;\n\n if (n % 7 != 0) {\n int extraDays = n % 7;\n int moneyToAdd = w + 1;\n for (int i = 0; i < extraDays; ++i) {\n money += moneyToAdd;\n moneyToAdd += 1;\n }\n }\n\n return money;\n }\n}\n```\n\n**UPVOTE IF HELPFuuL**\n\n![Screenshot 2023-12-05 at 6.18.22 AM.png](https://assets.leetcode.com/users/images/4fed8e49-27ed-40e3-a29b-4128bced273e_1701821876.0689087.png)\n
72
You are given the logs for users' actions on LeetCode, and an integer `k`. The logs are represented by a 2D integer array `logs` where each `logs[i] = [IDi, timei]` indicates that the user with `IDi` performed an action at the minute `timei`. **Multiple users** can perform actions simultaneously, and a single user can perform **multiple actions** in the same minute. The **user active minutes (UAM)** for a given user is defined as the **number of unique minutes** in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it. You are to calculate a **1-indexed** array `answer` of size `k` such that, for each `j` (`1 <= j <= k`), `answer[j]` is the **number of users** whose **UAM** equals `j`. Return _the array_ `answer` _as described above_. **Example 1:** **Input:** logs = \[\[0,5\],\[1,2\],\[0,2\],\[0,5\],\[1,3\]\], k = 5 **Output:** \[0,2,0,0,0\] **Explanation:** The user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once). The user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. Since both users have a UAM of 2, answer\[2\] is 2, and the remaining answer\[j\] values are 0. **Example 2:** **Input:** logs = \[\[1,1\],\[2,2\],\[2,3\]\], k = 4 **Output:** \[1,1,0,0\] **Explanation:** The user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1. The user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. There is one user with a UAM of 1 and one with a UAM of 2. Hence, answer\[1\] = 1, answer\[2\] = 1, and the remaining values are 0. **Constraints:** * `1 <= logs.length <= 104` * `0 <= IDi <= 109` * `1 <= timei <= 105` * `k` is in the range `[The maximum **UAM** for a user, 105]`.
Simulate the process by keeping track of how much money John is putting in and which day of the week it is, and use this information to deduce how much money John will put in the next day.
Simple Iteration
calculate-money-in-leetcode-bank
1
1
> If the remainder of the division of the ordinal number = 1, then it is Monday. \n\n> The amount of money on Monday is equal to the number of the week, on other days is equal to the previous one + 1\n\n### C++\n```cpp\npublic:\n int totalMoney(int n) {\n int totalMoney = 0;\n\n for (int day = 1, dailySum = 0, weeksCount = 0; day <= n; ++day) {\n if (day % 7 == 1) {\n weeksCount++;\n dailySum = weeksCount;\n }\n else\n dailySum++;\n\n totalMoney += dailySum;\n }\n\n return totalMoney;\n }\n```\n\n### Java\n```java\npublic int totalMoney(int n) {\n int totalMoney = 0;\n\n for (int day = 1, dailySum = 0, weeksCount = 0; day <= n; ++day) {\n if (day % 7 == 1) {\n weeksCount++;\n dailySum = weeksCount;\n }\n else\n dailySum++;\n\n totalMoney += dailySum;\n }\n\n return totalMoney;\n }\n```\n\n### Python\n```python\n def totalMoney(self, n: int) -> int:\n total_money, weeks_count, daily_sum = 0, 0, 0\n\n for day in range(1, n + 1):\n if day % 7 == 1:\n weeks_count += 1\n daily_sum = weeks_count\n else:\n daily_sum += 1\n\n total_money += daily_sum\n\n return total_money\n \n```\n\n[My github with algo repo](https://github.com/FLlGHT)\n
9
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**. He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put 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:** * `1 <= n <= 1000`
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
Simple Iteration
calculate-money-in-leetcode-bank
1
1
> If the remainder of the division of the ordinal number = 1, then it is Monday. \n\n> The amount of money on Monday is equal to the number of the week, on other days is equal to the previous one + 1\n\n### C++\n```cpp\npublic:\n int totalMoney(int n) {\n int totalMoney = 0;\n\n for (int day = 1, dailySum = 0, weeksCount = 0; day <= n; ++day) {\n if (day % 7 == 1) {\n weeksCount++;\n dailySum = weeksCount;\n }\n else\n dailySum++;\n\n totalMoney += dailySum;\n }\n\n return totalMoney;\n }\n```\n\n### Java\n```java\npublic int totalMoney(int n) {\n int totalMoney = 0;\n\n for (int day = 1, dailySum = 0, weeksCount = 0; day <= n; ++day) {\n if (day % 7 == 1) {\n weeksCount++;\n dailySum = weeksCount;\n }\n else\n dailySum++;\n\n totalMoney += dailySum;\n }\n\n return totalMoney;\n }\n```\n\n### Python\n```python\n def totalMoney(self, n: int) -> int:\n total_money, weeks_count, daily_sum = 0, 0, 0\n\n for day in range(1, n + 1):\n if day % 7 == 1:\n weeks_count += 1\n daily_sum = weeks_count\n else:\n daily_sum += 1\n\n total_money += daily_sum\n\n return total_money\n \n```\n\n[My github with algo repo](https://github.com/FLlGHT)\n
9
You are given the logs for users' actions on LeetCode, and an integer `k`. The logs are represented by a 2D integer array `logs` where each `logs[i] = [IDi, timei]` indicates that the user with `IDi` performed an action at the minute `timei`. **Multiple users** can perform actions simultaneously, and a single user can perform **multiple actions** in the same minute. The **user active minutes (UAM)** for a given user is defined as the **number of unique minutes** in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it. You are to calculate a **1-indexed** array `answer` of size `k` such that, for each `j` (`1 <= j <= k`), `answer[j]` is the **number of users** whose **UAM** equals `j`. Return _the array_ `answer` _as described above_. **Example 1:** **Input:** logs = \[\[0,5\],\[1,2\],\[0,2\],\[0,5\],\[1,3\]\], k = 5 **Output:** \[0,2,0,0,0\] **Explanation:** The user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once). The user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. Since both users have a UAM of 2, answer\[2\] is 2, and the remaining answer\[j\] values are 0. **Example 2:** **Input:** logs = \[\[1,1\],\[2,2\],\[2,3\]\], k = 4 **Output:** \[1,1,0,0\] **Explanation:** The user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1. The user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. There is one user with a UAM of 1 and one with a UAM of 2. Hence, answer\[1\] = 1, answer\[2\] = 1, and the remaining values are 0. **Constraints:** * `1 <= logs.length <= 104` * `0 <= IDi <= 109` * `1 <= timei <= 105` * `k` is in the range `[The maximum **UAM** for a user, 105]`.
Simulate the process by keeping track of how much money John is putting in and which day of the week it is, and use this information to deduce how much money John will put in the next day.
✅☑[C++/Java/Python/JavaScript] || 3 Approaches || Beats 100% || EXPLAINED🔥
calculate-money-in-leetcode-bank
1
1
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1(Simulate)***\n1. **Variables Initialization:** `ans` is initialized to zero to store the total money earned. `monday` represents the amount earned on Mondays, starting from 1.\n\n1. **Main Loop:** The `while` loop continues until \'n\' days are exhausted. It processes the earnings for each week.\n\n1. **Inner Loop:** The inner `for` loop iterates through each day of the week or until \'n\' days are left (whichever is smaller). For each day, it increments `ans` by the amount earned on that day, which starts with the amount earned on Monday and increases as the week progresses.\n\n1. **Updating \'n\' and \'monday\':** After processing a week, `n` is reduced by 7 (representing a week), and `monday` is incremented by 1 for the next week\'s earnings.\n\n1. **Return:** Finally, the total `ans` representing the total amount earned over \'n\' days is returned.\n\n# Complexity\n- *Time complexity:*\n $$O(n)$$\n \n\n- *Space complexity:*\n $$O(1)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int totalMoney(int n) {\n int ans = 0; // Variable to store the total money earned\n int monday = 1; // Represents the amount earned on Monday\n \n while (n > 0) { // Continue the loop until \'n\' days are exhausted\n for (int day = 0; day < min(n, 7); day++) { // Iterate for each day of the week or until \'n\' days are left\n ans += monday + day; // Increment \'ans\' by the amount earned on the current day (monday + day)\n }\n \n n -= 7; // Deduct 7 days (a week) from the total number of days left\n monday++; // Increment the amount earned on Monday for the next week\n }\n \n return ans; // Return the total amount earned over \'n\' days\n }\n};\n\n\n\n```\n```C []\nint min(int a, int b) {\n return (a < b) ? a : b;\n}\n\nint totalMoney(int n) {\n int ans = 0; // Variable to store the total money earned\n int monday = 1; // Represents the amount earned on Monday\n \n while (n > 0) { // Continue the loop until \'n\' days are exhausted\n for (int day = 0; day < (n < 7 ? n : 7); day++) { // Iterate for each day of the week or until \'n\' days are left\n ans += monday + day; // Increment \'ans\' by the amount earned on the current day (monday + day)\n }\n \n n -= 7; // Deduct 7 days (a week) from the total number of days left\n monday++; // Increment the amount earned on Monday for the next week\n }\n \n return ans; // Return the total amount earned over \'n\' days\n}\n\n\n\n```\n```Java []\nclass Solution {\n public int totalMoney(int n) {\n int ans = 0;\n int monday = 1;\n \n while (n > 0) {\n for (int day = 0; day < Math.min(n, 7); day++) {\n ans += monday + day;\n }\n \n n -= 7;\n monday++;\n }\n \n return ans;\n }\n}\n\n\n```\n```python3 []\nclass Solution:\n def totalMoney(self, n: int) -> int:\n ans = 0\n monday = 1\n \n while n > 0:\n for day in range(min(n, 7)):\n ans += monday + day\n \n n -= 7\n monday += 1\n\n return ans\n\n\n```\n```javascript []\nfunction totalMoney(n) {\n let ans = 0; // Variable to store the total money earned\n let monday = 1; // Represents the amount earned on Monday\n \n while (n > 0) { // Continue the loop until \'n\' days are exhausted\n for (let day = 0; day < Math.min(n, 7); day++) { // Iterate for each day of the week or until \'n\' days are left\n ans += monday + day; // Increment \'ans\' by the amount earned on the current day (monday + day)\n }\n \n n -= 7; // Deduct 7 days (a week) from the total number of days left\n monday++; // Increment the amount earned on Monday for the next week\n }\n \n return ans; // Return the total amount earned over \'n\' days\n}\n\n```\n\n---\n\n#### ***Approach 2(Math Approach 1)***\n1.**Variable Initialization:** Initialize `ans` to store the total money earned. Calculate `weeks` as the number of complete weeks in `n` days and `days` as the remaining days.\n\n1.**Calculation of Money Earned from Complete Weeks:** Use the formula for an arithmetic series to calculate the total money earned from complete weeks. The pattern follows an arithmetic sequence where each week\'s earnings form an increasing sequence starting from `28` and increasing by `7` each week (`28, 35, 42, ...`).\n\n1.**Calculation of Money Earned from Remaining Days:** Calculate the total money earned from the remaining days after complete weeks. The amount earned on the first day of the remaining days is `weeks + 1`. Use the formula for the sum of an arithmetic series to calculate the total earnings for the remaining days.\n\n1. **Return:** Return the total earnings calculated (`ans`).\n\n# Complexity\n- *Time complexity:*\n $$O(1)$$\n \n\n- *Space complexity:*\n $$O(1)$$\n \n\n\n# Code\n```C++ []\n\nclass Solution {\npublic:\n int totalMoney(int n) {\n int ans = 0;\n int weeks = n / 7; // Calculate the number of complete weeks\n int days = n % 7; // Calculate the remaining days\n \n // Calculate the total money earned from complete weeks\n // Using the formula for an arithmetic series: sum = n * (a1 + an) / 2\n ans += 28 * weeks + 7 * (weeks - 1) * weeks / 2; // 28 + 35 + 42 + ... + (28 + 7 * (weeks - 1))\n \n // Calculate the total money earned from remaining days\n // Starting from the next day after the last complete week\n int startMoney = weeks + 1; // Money earned on the first day of the remaining days\n ans += (startMoney + startMoney + days - 1) * days / 2; // a1 + an = (a1 + an) * n / 2\n\n return ans;\n }\n};\n\n\n```\n```C []\n\n\nint totalMoney(int n) {\n int ans = 0;\n int weeks = n / 7; // Calculate the number of complete weeks\n int days = n % 7; // Calculate the remaining days\n \n // Calculate the total money earned from complete weeks\n // Using the formula for an arithmetic series: sum = n * (a1 + an) / 2\n ans += 28 * weeks + 7 * (weeks - 1) * weeks / 2; // 28 + 35 + 42 + ... + (28 + 7 * (weeks - 1))\n \n // Calculate the total money earned from remaining days\n // Starting from the next day after the last complete week\n int startMoney = weeks + 1; // Money earned on the first day of the remaining days\n ans += (startMoney + startMoney + days - 1) * days / 2; // a1 + an = (a1 + an) * n / 2\n\n return ans;\n}\n\n\n```\n```Java []\n\nclass Solution {\n public int totalMoney(int n) {\n int ans = 0;\n int weeks = n / 7; // Calculate the number of complete weeks\n int days = n % 7; // Calculate the remaining days\n \n // Calculate the total money earned from complete weeks\n // Using the formula for an arithmetic series: sum = n * (a1 + an) / 2\n ans += 28 * weeks + 7 * (weeks - 1) * weeks / 2; // 28 + 35 + 42 + ... + (28 + 7 * (weeks - 1))\n \n // Calculate the total money earned from remaining days\n // Starting from the next day after the last complete week\n int startMoney = weeks + 1; // Money earned on the first day of the remaining days\n ans += (startMoney + startMoney + days - 1) * days / 2; // a1 + an = (a1 + an) * n / 2\n\n return ans;\n }\n}\n\n\n```\n```python3 []\nclass Solution:\n def totalMoney(self, n: int) -> int:\n ans = 0\n weeks = n // 7 # Calculate the number of complete weeks\n days = n % 7 # Calculate the remaining days\n \n # Calculate the total money earned from complete weeks\n # Using the formula for an arithmetic series: sum = n * (a1 + an) / 2\n ans += 28 * weeks + 7 * (weeks - 1) * weeks // 2 # 28 + 35 + 42 + ... + (28 + 7 * (weeks - 1))\n \n # Calculate the total money earned from remaining days\n # Starting from the next day after the last complete week\n startMoney = weeks + 1 # Money earned on the first day of the remaining days\n ans += (startMoney + startMoney + days - 1) * days // 2 # a1 + an = (a1 + an) * n // 2\n\n return ans\n\n\n\n```\n```javascript []\nfunction totalMoney(n) {\n let ans = 0;\n let weeks = Math.floor(n / 7); // Calculate the number of complete weeks\n let days = n % 7; // Calculate the remaining days\n \n // Calculate the total money earned from complete weeks\n // Using the formula for an arithmetic series: sum = n * (a1 + an) / 2\n ans += 28 * weeks + 7 * (weeks - 1) * weeks / 2; // 28 + 35 + 42 + ... + (28 + 7 * (weeks - 1))\n \n // Calculate the total money earned from remaining days\n // Starting from the next day after the last complete week\n let startMoney = weeks + 1; // Money earned on the first day of the remaining days\n ans += (startMoney + startMoney + days - 1) * days / 2; // a1 + an = (a1 + an) * n / 2\n\n return ans;\n}\n\n```\n\n---\n#### ***Approach 3(Math Approach 2)***\n\n1. **Calculation of Complete Weeks:** Calculate the number of complete weeks (`k`) in \'n\' days.\n\n1. **Calculation of Earnings from Complete Weeks:** Set `F` as the initial earning for the first week and `L` as the earning for the last week. Use the arithmetic series formula `sum = n * (a1 + an) / 2` to calculate the total earnings from complete weeks (`arithmeticSum`).\n\n1. **Calculation of Earnings for the Final Incomplete Week:**\n\n - Initialize `monday` as the earnings on Monday for the final week.\n - Iterate through the days of the final incomplete week (remainder of \'n\' days divided by 7).\n - For each day, increment `finalWeek` with earnings starting from `monday` and increasing by the day\'s number.\n1. **Return Total Earnings:** Return the sum of earnings from complete weeks and the final incomplete week as the total earnings for \'n\' days.\n\n# Complexity\n- *Time complexity:*\n $$O(1)$$\n \n\n- *Space complexity:*\n $$O(1)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int totalMoney(int n) {\n int k = n / 7; // Calculate the number of complete weeks\n int F = 28; // Initial earning for the first week\n int L = 28 + (k - 1) * 7; // Earning for the last week\n int arithmeticSum = k * (F + L) / 2; // Calculate the total earnings from complete weeks using arithmetic series formula\n \n int monday = 1 + k; // Earnings on Monday for the final week\n int finalWeek = 0;\n \n // Calculate earnings for the final incomplete week\n for (int day = 0; day < n % 7; day++) {\n finalWeek += monday + day; // Increment earnings for each day of the final incomplete week\n }\n \n return arithmeticSum + finalWeek; // Return the total earnings for \'n\' days\n }\n};\n\n\n\n```\n```C []\n#include <stdio.h>\n\nint totalMoney(int n) {\n int k = n / 7; // Calculate the number of complete weeks\n int F = 28; // Initial earning for the first week\n int L = 28 + (k - 1) * 7; // Earning for the last week\n int arithmeticSum = k * (F + L) / 2; // Calculate the total earnings from complete weeks using arithmetic series formula\n \n int monday = 1 + k; // Earnings on Monday for the final week\n int finalWeek = 0;\n \n // Calculate earnings for the final incomplete week\n for (int day = 0; day < n % 7; day++) {\n finalWeek += monday + day; // Increment earnings for each day of the final incomplete week\n }\n \n return arithmeticSum + finalWeek; // Return the total earnings for \'n\' days\n}\n\n\n\n\n\n\n```\n```Java []\nclass Solution {\n public int totalMoney(int n) {\n int k = n / 7;\n int F = 28;\n int L = 28 + (k - 1) * 7;\n int arithmeticSum = k * (F + L) / 2;\n \n int monday = 1 + k;\n int finalWeek = 0;\n for (int day = 0; day < n % 7; day++) {\n finalWeek += monday + day;\n }\n \n return arithmeticSum + finalWeek;\n }\n}\n\n\n```\n```python3 []\nclass Solution:\n def totalMoney(self, n: int) -> int:\n k = n // 7\n F = 28\n L = 28 + (k - 1) * 7\n arithmetic_sum = k * (F + L) // 2\n \n monday = 1 + k\n final_week = 0\n for day in range(n % 7):\n final_week += monday + day\n \n return arithmetic_sum + final_week\n\n\n```\n```javascript []\nfunction totalMoney(n) {\n let k = Math.floor(n / 7); // Calculate the number of complete weeks\n let F = 28; // Initial earning for the first week\n let L = 28 + (k - 1) * 7; // Earning for the last week\n let arithmeticSum = k * (F + L) / 2; // Calculate the total earnings from complete weeks using arithmetic series formula\n \n let monday = 1 + k; // Earnings on Monday for the final week\n let finalWeek = 0;\n \n // Calculate earnings for the final incomplete week\n for (let day = 0; day < n % 7; day++) {\n finalWeek += monday + day; // Increment earnings for each day of the final incomplete week\n }\n \n return arithmeticSum + finalWeek; // Return the total earnings for \'n\' days\n}\n\n```\n\n---\n\n\n# PLEASE UPVOTE IF IT HELPED\n\n---\n---\n\n\n---
17
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**. He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put 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:** * `1 <= n <= 1000`
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
✅☑[C++/Java/Python/JavaScript] || 3 Approaches || Beats 100% || EXPLAINED🔥
calculate-money-in-leetcode-bank
1
1
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1(Simulate)***\n1. **Variables Initialization:** `ans` is initialized to zero to store the total money earned. `monday` represents the amount earned on Mondays, starting from 1.\n\n1. **Main Loop:** The `while` loop continues until \'n\' days are exhausted. It processes the earnings for each week.\n\n1. **Inner Loop:** The inner `for` loop iterates through each day of the week or until \'n\' days are left (whichever is smaller). For each day, it increments `ans` by the amount earned on that day, which starts with the amount earned on Monday and increases as the week progresses.\n\n1. **Updating \'n\' and \'monday\':** After processing a week, `n` is reduced by 7 (representing a week), and `monday` is incremented by 1 for the next week\'s earnings.\n\n1. **Return:** Finally, the total `ans` representing the total amount earned over \'n\' days is returned.\n\n# Complexity\n- *Time complexity:*\n $$O(n)$$\n \n\n- *Space complexity:*\n $$O(1)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int totalMoney(int n) {\n int ans = 0; // Variable to store the total money earned\n int monday = 1; // Represents the amount earned on Monday\n \n while (n > 0) { // Continue the loop until \'n\' days are exhausted\n for (int day = 0; day < min(n, 7); day++) { // Iterate for each day of the week or until \'n\' days are left\n ans += monday + day; // Increment \'ans\' by the amount earned on the current day (monday + day)\n }\n \n n -= 7; // Deduct 7 days (a week) from the total number of days left\n monday++; // Increment the amount earned on Monday for the next week\n }\n \n return ans; // Return the total amount earned over \'n\' days\n }\n};\n\n\n\n```\n```C []\nint min(int a, int b) {\n return (a < b) ? a : b;\n}\n\nint totalMoney(int n) {\n int ans = 0; // Variable to store the total money earned\n int monday = 1; // Represents the amount earned on Monday\n \n while (n > 0) { // Continue the loop until \'n\' days are exhausted\n for (int day = 0; day < (n < 7 ? n : 7); day++) { // Iterate for each day of the week or until \'n\' days are left\n ans += monday + day; // Increment \'ans\' by the amount earned on the current day (monday + day)\n }\n \n n -= 7; // Deduct 7 days (a week) from the total number of days left\n monday++; // Increment the amount earned on Monday for the next week\n }\n \n return ans; // Return the total amount earned over \'n\' days\n}\n\n\n\n```\n```Java []\nclass Solution {\n public int totalMoney(int n) {\n int ans = 0;\n int monday = 1;\n \n while (n > 0) {\n for (int day = 0; day < Math.min(n, 7); day++) {\n ans += monday + day;\n }\n \n n -= 7;\n monday++;\n }\n \n return ans;\n }\n}\n\n\n```\n```python3 []\nclass Solution:\n def totalMoney(self, n: int) -> int:\n ans = 0\n monday = 1\n \n while n > 0:\n for day in range(min(n, 7)):\n ans += monday + day\n \n n -= 7\n monday += 1\n\n return ans\n\n\n```\n```javascript []\nfunction totalMoney(n) {\n let ans = 0; // Variable to store the total money earned\n let monday = 1; // Represents the amount earned on Monday\n \n while (n > 0) { // Continue the loop until \'n\' days are exhausted\n for (let day = 0; day < Math.min(n, 7); day++) { // Iterate for each day of the week or until \'n\' days are left\n ans += monday + day; // Increment \'ans\' by the amount earned on the current day (monday + day)\n }\n \n n -= 7; // Deduct 7 days (a week) from the total number of days left\n monday++; // Increment the amount earned on Monday for the next week\n }\n \n return ans; // Return the total amount earned over \'n\' days\n}\n\n```\n\n---\n\n#### ***Approach 2(Math Approach 1)***\n1.**Variable Initialization:** Initialize `ans` to store the total money earned. Calculate `weeks` as the number of complete weeks in `n` days and `days` as the remaining days.\n\n1.**Calculation of Money Earned from Complete Weeks:** Use the formula for an arithmetic series to calculate the total money earned from complete weeks. The pattern follows an arithmetic sequence where each week\'s earnings form an increasing sequence starting from `28` and increasing by `7` each week (`28, 35, 42, ...`).\n\n1.**Calculation of Money Earned from Remaining Days:** Calculate the total money earned from the remaining days after complete weeks. The amount earned on the first day of the remaining days is `weeks + 1`. Use the formula for the sum of an arithmetic series to calculate the total earnings for the remaining days.\n\n1. **Return:** Return the total earnings calculated (`ans`).\n\n# Complexity\n- *Time complexity:*\n $$O(1)$$\n \n\n- *Space complexity:*\n $$O(1)$$\n \n\n\n# Code\n```C++ []\n\nclass Solution {\npublic:\n int totalMoney(int n) {\n int ans = 0;\n int weeks = n / 7; // Calculate the number of complete weeks\n int days = n % 7; // Calculate the remaining days\n \n // Calculate the total money earned from complete weeks\n // Using the formula for an arithmetic series: sum = n * (a1 + an) / 2\n ans += 28 * weeks + 7 * (weeks - 1) * weeks / 2; // 28 + 35 + 42 + ... + (28 + 7 * (weeks - 1))\n \n // Calculate the total money earned from remaining days\n // Starting from the next day after the last complete week\n int startMoney = weeks + 1; // Money earned on the first day of the remaining days\n ans += (startMoney + startMoney + days - 1) * days / 2; // a1 + an = (a1 + an) * n / 2\n\n return ans;\n }\n};\n\n\n```\n```C []\n\n\nint totalMoney(int n) {\n int ans = 0;\n int weeks = n / 7; // Calculate the number of complete weeks\n int days = n % 7; // Calculate the remaining days\n \n // Calculate the total money earned from complete weeks\n // Using the formula for an arithmetic series: sum = n * (a1 + an) / 2\n ans += 28 * weeks + 7 * (weeks - 1) * weeks / 2; // 28 + 35 + 42 + ... + (28 + 7 * (weeks - 1))\n \n // Calculate the total money earned from remaining days\n // Starting from the next day after the last complete week\n int startMoney = weeks + 1; // Money earned on the first day of the remaining days\n ans += (startMoney + startMoney + days - 1) * days / 2; // a1 + an = (a1 + an) * n / 2\n\n return ans;\n}\n\n\n```\n```Java []\n\nclass Solution {\n public int totalMoney(int n) {\n int ans = 0;\n int weeks = n / 7; // Calculate the number of complete weeks\n int days = n % 7; // Calculate the remaining days\n \n // Calculate the total money earned from complete weeks\n // Using the formula for an arithmetic series: sum = n * (a1 + an) / 2\n ans += 28 * weeks + 7 * (weeks - 1) * weeks / 2; // 28 + 35 + 42 + ... + (28 + 7 * (weeks - 1))\n \n // Calculate the total money earned from remaining days\n // Starting from the next day after the last complete week\n int startMoney = weeks + 1; // Money earned on the first day of the remaining days\n ans += (startMoney + startMoney + days - 1) * days / 2; // a1 + an = (a1 + an) * n / 2\n\n return ans;\n }\n}\n\n\n```\n```python3 []\nclass Solution:\n def totalMoney(self, n: int) -> int:\n ans = 0\n weeks = n // 7 # Calculate the number of complete weeks\n days = n % 7 # Calculate the remaining days\n \n # Calculate the total money earned from complete weeks\n # Using the formula for an arithmetic series: sum = n * (a1 + an) / 2\n ans += 28 * weeks + 7 * (weeks - 1) * weeks // 2 # 28 + 35 + 42 + ... + (28 + 7 * (weeks - 1))\n \n # Calculate the total money earned from remaining days\n # Starting from the next day after the last complete week\n startMoney = weeks + 1 # Money earned on the first day of the remaining days\n ans += (startMoney + startMoney + days - 1) * days // 2 # a1 + an = (a1 + an) * n // 2\n\n return ans\n\n\n\n```\n```javascript []\nfunction totalMoney(n) {\n let ans = 0;\n let weeks = Math.floor(n / 7); // Calculate the number of complete weeks\n let days = n % 7; // Calculate the remaining days\n \n // Calculate the total money earned from complete weeks\n // Using the formula for an arithmetic series: sum = n * (a1 + an) / 2\n ans += 28 * weeks + 7 * (weeks - 1) * weeks / 2; // 28 + 35 + 42 + ... + (28 + 7 * (weeks - 1))\n \n // Calculate the total money earned from remaining days\n // Starting from the next day after the last complete week\n let startMoney = weeks + 1; // Money earned on the first day of the remaining days\n ans += (startMoney + startMoney + days - 1) * days / 2; // a1 + an = (a1 + an) * n / 2\n\n return ans;\n}\n\n```\n\n---\n#### ***Approach 3(Math Approach 2)***\n\n1. **Calculation of Complete Weeks:** Calculate the number of complete weeks (`k`) in \'n\' days.\n\n1. **Calculation of Earnings from Complete Weeks:** Set `F` as the initial earning for the first week and `L` as the earning for the last week. Use the arithmetic series formula `sum = n * (a1 + an) / 2` to calculate the total earnings from complete weeks (`arithmeticSum`).\n\n1. **Calculation of Earnings for the Final Incomplete Week:**\n\n - Initialize `monday` as the earnings on Monday for the final week.\n - Iterate through the days of the final incomplete week (remainder of \'n\' days divided by 7).\n - For each day, increment `finalWeek` with earnings starting from `monday` and increasing by the day\'s number.\n1. **Return Total Earnings:** Return the sum of earnings from complete weeks and the final incomplete week as the total earnings for \'n\' days.\n\n# Complexity\n- *Time complexity:*\n $$O(1)$$\n \n\n- *Space complexity:*\n $$O(1)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int totalMoney(int n) {\n int k = n / 7; // Calculate the number of complete weeks\n int F = 28; // Initial earning for the first week\n int L = 28 + (k - 1) * 7; // Earning for the last week\n int arithmeticSum = k * (F + L) / 2; // Calculate the total earnings from complete weeks using arithmetic series formula\n \n int monday = 1 + k; // Earnings on Monday for the final week\n int finalWeek = 0;\n \n // Calculate earnings for the final incomplete week\n for (int day = 0; day < n % 7; day++) {\n finalWeek += monday + day; // Increment earnings for each day of the final incomplete week\n }\n \n return arithmeticSum + finalWeek; // Return the total earnings for \'n\' days\n }\n};\n\n\n\n```\n```C []\n#include <stdio.h>\n\nint totalMoney(int n) {\n int k = n / 7; // Calculate the number of complete weeks\n int F = 28; // Initial earning for the first week\n int L = 28 + (k - 1) * 7; // Earning for the last week\n int arithmeticSum = k * (F + L) / 2; // Calculate the total earnings from complete weeks using arithmetic series formula\n \n int monday = 1 + k; // Earnings on Monday for the final week\n int finalWeek = 0;\n \n // Calculate earnings for the final incomplete week\n for (int day = 0; day < n % 7; day++) {\n finalWeek += monday + day; // Increment earnings for each day of the final incomplete week\n }\n \n return arithmeticSum + finalWeek; // Return the total earnings for \'n\' days\n}\n\n\n\n\n\n\n```\n```Java []\nclass Solution {\n public int totalMoney(int n) {\n int k = n / 7;\n int F = 28;\n int L = 28 + (k - 1) * 7;\n int arithmeticSum = k * (F + L) / 2;\n \n int monday = 1 + k;\n int finalWeek = 0;\n for (int day = 0; day < n % 7; day++) {\n finalWeek += monday + day;\n }\n \n return arithmeticSum + finalWeek;\n }\n}\n\n\n```\n```python3 []\nclass Solution:\n def totalMoney(self, n: int) -> int:\n k = n // 7\n F = 28\n L = 28 + (k - 1) * 7\n arithmetic_sum = k * (F + L) // 2\n \n monday = 1 + k\n final_week = 0\n for day in range(n % 7):\n final_week += monday + day\n \n return arithmetic_sum + final_week\n\n\n```\n```javascript []\nfunction totalMoney(n) {\n let k = Math.floor(n / 7); // Calculate the number of complete weeks\n let F = 28; // Initial earning for the first week\n let L = 28 + (k - 1) * 7; // Earning for the last week\n let arithmeticSum = k * (F + L) / 2; // Calculate the total earnings from complete weeks using arithmetic series formula\n \n let monday = 1 + k; // Earnings on Monday for the final week\n let finalWeek = 0;\n \n // Calculate earnings for the final incomplete week\n for (let day = 0; day < n % 7; day++) {\n finalWeek += monday + day; // Increment earnings for each day of the final incomplete week\n }\n \n return arithmeticSum + finalWeek; // Return the total earnings for \'n\' days\n}\n\n```\n\n---\n\n\n# PLEASE UPVOTE IF IT HELPED\n\n---\n---\n\n\n---
17
You are given the logs for users' actions on LeetCode, and an integer `k`. The logs are represented by a 2D integer array `logs` where each `logs[i] = [IDi, timei]` indicates that the user with `IDi` performed an action at the minute `timei`. **Multiple users** can perform actions simultaneously, and a single user can perform **multiple actions** in the same minute. The **user active minutes (UAM)** for a given user is defined as the **number of unique minutes** in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it. You are to calculate a **1-indexed** array `answer` of size `k` such that, for each `j` (`1 <= j <= k`), `answer[j]` is the **number of users** whose **UAM** equals `j`. Return _the array_ `answer` _as described above_. **Example 1:** **Input:** logs = \[\[0,5\],\[1,2\],\[0,2\],\[0,5\],\[1,3\]\], k = 5 **Output:** \[0,2,0,0,0\] **Explanation:** The user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once). The user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. Since both users have a UAM of 2, answer\[2\] is 2, and the remaining answer\[j\] values are 0. **Example 2:** **Input:** logs = \[\[1,1\],\[2,2\],\[2,3\]\], k = 4 **Output:** \[1,1,0,0\] **Explanation:** The user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1. The user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. There is one user with a UAM of 1 and one with a UAM of 2. Hence, answer\[1\] = 1, answer\[2\] = 1, and the remaining values are 0. **Constraints:** * `1 <= logs.length <= 104` * `0 <= IDi <= 109` * `1 <= timei <= 105` * `k` is in the range `[The maximum **UAM** for a user, 105]`.
Simulate the process by keeping track of how much money John is putting in and which day of the week it is, and use this information to deduce how much money John will put in the next day.
Arithmetic Progression O(1)Handwriting||0ms Beats 100%
calculate-money-in-leetcode-bank
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nArithmetic Progression\nConsider the arithmetic progression \n$$\na, a+d, a+2d,\\cdots, e=a+(r-1)d\n$$\nThe sum is $\\frac{(a+e)r}{2}$. \n# Approach\n[Please turn on English subtitles if necessary]\n[https://youtu.be/TqKZGAHLKdw?si=FzWxIkiRxqOtcOX8](https://youtu.be/TqKZGAHLKdw?si=FzWxIkiRxqOtcOX8)\n![1716. Calculate Money in Leetcode Bank.jpg](https://assets.leetcode.com/users/images/6fd94b87-9f41-4587-9dfe-44679e67a996_1701823029.1111803.jpeg)\n\nThe 2nd version defines a function computing the sum for arithmetic progression\n```\n int arithmeticProgression(int leading, int last, int terms){\n return (leading+last)*terms/2;\n }\n```\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n# Code\n```C++ []\n#pragma GCC optimize("O3", "unroll-loops")\nclass Solution {\npublic:\n int totalMoney(int n) {\n auto [q, r]=div(n, 7);\n return 28*q+7*q*(q-1)/2+(2*q+r+1)*r/2;\n }\n};\nauto init = []()\n{ \n ios::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n return \'c\';\n}();\n```\n```python []\nclass Solution:\n def totalMoney(self, n: int) -> int:\n q, r= divmod(n, 7)\n return 28*q+7*q*(q-1)//2+(2*q+r+1)*r//2\n \n```\n# 2nd C++ Version with function arithmeticProgression runs in 0ms & beats 100%\n\n```python []\nclass Solution:\n def totalMoney(self, n: int) -> int:\n def arithmeticProgression(leading, last, terms):\n return (leading+last)*terms//2\n q, r= divmod(n, 7)\n return arithmeticProgression(28, 28+(q-1)*7, q)+arithmeticProgression(q+1, q+r, r)\n \n```\n```C++ []\nclass Solution {\npublic:\n int arithmeticProgression(int leading, int last, int terms){\n return (leading+last)*terms/2;\n }\n int totalMoney(int n) {\n auto [q, r]=div(n, 7);\n return arithmeticProgression(28, 28+(q-1)*7, q)+arithmeticProgression(q+1, q+r, r);\n }\n};\n```\n
7
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**. He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put 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:** * `1 <= n <= 1000`
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
Arithmetic Progression O(1)Handwriting||0ms Beats 100%
calculate-money-in-leetcode-bank
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nArithmetic Progression\nConsider the arithmetic progression \n$$\na, a+d, a+2d,\\cdots, e=a+(r-1)d\n$$\nThe sum is $\\frac{(a+e)r}{2}$. \n# Approach\n[Please turn on English subtitles if necessary]\n[https://youtu.be/TqKZGAHLKdw?si=FzWxIkiRxqOtcOX8](https://youtu.be/TqKZGAHLKdw?si=FzWxIkiRxqOtcOX8)\n![1716. Calculate Money in Leetcode Bank.jpg](https://assets.leetcode.com/users/images/6fd94b87-9f41-4587-9dfe-44679e67a996_1701823029.1111803.jpeg)\n\nThe 2nd version defines a function computing the sum for arithmetic progression\n```\n int arithmeticProgression(int leading, int last, int terms){\n return (leading+last)*terms/2;\n }\n```\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n# Code\n```C++ []\n#pragma GCC optimize("O3", "unroll-loops")\nclass Solution {\npublic:\n int totalMoney(int n) {\n auto [q, r]=div(n, 7);\n return 28*q+7*q*(q-1)/2+(2*q+r+1)*r/2;\n }\n};\nauto init = []()\n{ \n ios::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n return \'c\';\n}();\n```\n```python []\nclass Solution:\n def totalMoney(self, n: int) -> int:\n q, r= divmod(n, 7)\n return 28*q+7*q*(q-1)//2+(2*q+r+1)*r//2\n \n```\n# 2nd C++ Version with function arithmeticProgression runs in 0ms & beats 100%\n\n```python []\nclass Solution:\n def totalMoney(self, n: int) -> int:\n def arithmeticProgression(leading, last, terms):\n return (leading+last)*terms//2\n q, r= divmod(n, 7)\n return arithmeticProgression(28, 28+(q-1)*7, q)+arithmeticProgression(q+1, q+r, r)\n \n```\n```C++ []\nclass Solution {\npublic:\n int arithmeticProgression(int leading, int last, int terms){\n return (leading+last)*terms/2;\n }\n int totalMoney(int n) {\n auto [q, r]=div(n, 7);\n return arithmeticProgression(28, 28+(q-1)*7, q)+arithmeticProgression(q+1, q+r, r);\n }\n};\n```\n
7
You are given the logs for users' actions on LeetCode, and an integer `k`. The logs are represented by a 2D integer array `logs` where each `logs[i] = [IDi, timei]` indicates that the user with `IDi` performed an action at the minute `timei`. **Multiple users** can perform actions simultaneously, and a single user can perform **multiple actions** in the same minute. The **user active minutes (UAM)** for a given user is defined as the **number of unique minutes** in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it. You are to calculate a **1-indexed** array `answer` of size `k` such that, for each `j` (`1 <= j <= k`), `answer[j]` is the **number of users** whose **UAM** equals `j`. Return _the array_ `answer` _as described above_. **Example 1:** **Input:** logs = \[\[0,5\],\[1,2\],\[0,2\],\[0,5\],\[1,3\]\], k = 5 **Output:** \[0,2,0,0,0\] **Explanation:** The user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once). The user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. Since both users have a UAM of 2, answer\[2\] is 2, and the remaining answer\[j\] values are 0. **Example 2:** **Input:** logs = \[\[1,1\],\[2,2\],\[2,3\]\], k = 4 **Output:** \[1,1,0,0\] **Explanation:** The user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1. The user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. There is one user with a UAM of 1 and one with a UAM of 2. Hence, answer\[1\] = 1, answer\[2\] = 1, and the remaining values are 0. **Constraints:** * `1 <= logs.length <= 104` * `0 <= IDi <= 109` * `1 <= timei <= 105` * `k` is in the range `[The maximum **UAM** for a user, 105]`.
Simulate the process by keeping track of how much money John is putting in and which day of the week it is, and use this information to deduce how much money John will put in the next day.
💯Faster✅💯 Easy solution to understand [python, c#, Java, Rust] 🔥🔥
calculate-money-in-leetcode-bank
1
1
# Description\n\nHercy wants to save money for his first car. He puts money in the Leetcode bank every day.\n\nHe starts by putting in 1 dollar on Monday, the first day. Every day from Tuesday to Sunday, he will put in 1 dollar 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.\n\n## Intuition\n\nThe problem involves a repetitive pattern where Hercy saves money with increasing amounts every day and resets to a higher amount every Monday. To solve this, we need to calculate the total amount saved by considering complete weeks and any remaining days.\n\n## Approach\n\nThe approach is to iterate through the weeks and calculate the total amount saved for each week. The first loop handles complete weeks, adding a constant value for the week and the increasing amounts for each day within that week. The second loop deals with the remaining days, calculating the total amount for each day.\n\n## Complexity\n\n- Time complexity: O(n)\n - The code iterates through the days once, either in complete weeks or the remaining days, resulting in a linear time complexity.\n- Space complexity: O(1)\n - The code uses a constant amount of space, independent of the input size. There are no additional data structures that depend on the input size.\n\n## Performance\n| Language | Execution Time (ms) | Memory Usage (MB) |\n| :--- | :---:| :---: | \nJava | 0 | 39.6 |\nPython3 | 42 | 16.3 |\nC# | 27 | 26.9 |\nRust | 0 | 2 |\n\n# Code\n```python []\nclass Solution:\n def totalMoney(self, n: int) -> int:\n result = 0\n it = n // 7\n for i in range(it):\n result += 28 + (i * 7)\n \n mod = n - it * 7\n \n it += 1\n\n for i in range(mod):\n result += (i + it)\n \n return result\n```\n```C# []\npublic class Solution {\n public int TotalMoney(int n) {\n int result = 0;\n int it = n / 7;\n\n for (int i = 0; i < it; i++) {\n result += 28 + (i * 7);\n }\n\n int mod = n - it * 7;\n it += 1;\n\n for (int i = 0; i < mod; i++) {\n result += (i + it);\n }\n\n return result;\n }\n}\n```\n```Java []\npublic class Solution {\n public int totalMoney(int n) {\n int result = 0;\n int it = n / 7;\n \n for (int i = 0; i < it; i++) {\n result += 28 + (i * 7);\n }\n \n int mod = n - it * 7;\n it += 1;\n\n for (int i = 0; i < mod; i++) {\n result += (i + it);\n }\n\n return result;\n }\n}\n```\n``` Rust []\nimpl Solution {\n pub fn total_money(n: i32) -> i32 {\n let mut result = 0;\n let it = n / 7;\n\n for i in 0..it {\n result += 28 + (i * 7);\n }\n\n let mod_value = n - it * 7;\n let mut it = it + 1;\n\n for i in 0..mod_value {\n result += i + it;\n }\n\n result\n }\n}\n```\n![image name](https://i.imgur.com/JdL5kBI.gif)\n\n- Please upvote me !!!
7
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**. He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put 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:** * `1 <= n <= 1000`
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
💯Faster✅💯 Easy solution to understand [python, c#, Java, Rust] 🔥🔥
calculate-money-in-leetcode-bank
1
1
# Description\n\nHercy wants to save money for his first car. He puts money in the Leetcode bank every day.\n\nHe starts by putting in 1 dollar on Monday, the first day. Every day from Tuesday to Sunday, he will put in 1 dollar 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.\n\n## Intuition\n\nThe problem involves a repetitive pattern where Hercy saves money with increasing amounts every day and resets to a higher amount every Monday. To solve this, we need to calculate the total amount saved by considering complete weeks and any remaining days.\n\n## Approach\n\nThe approach is to iterate through the weeks and calculate the total amount saved for each week. The first loop handles complete weeks, adding a constant value for the week and the increasing amounts for each day within that week. The second loop deals with the remaining days, calculating the total amount for each day.\n\n## Complexity\n\n- Time complexity: O(n)\n - The code iterates through the days once, either in complete weeks or the remaining days, resulting in a linear time complexity.\n- Space complexity: O(1)\n - The code uses a constant amount of space, independent of the input size. There are no additional data structures that depend on the input size.\n\n## Performance\n| Language | Execution Time (ms) | Memory Usage (MB) |\n| :--- | :---:| :---: | \nJava | 0 | 39.6 |\nPython3 | 42 | 16.3 |\nC# | 27 | 26.9 |\nRust | 0 | 2 |\n\n# Code\n```python []\nclass Solution:\n def totalMoney(self, n: int) -> int:\n result = 0\n it = n // 7\n for i in range(it):\n result += 28 + (i * 7)\n \n mod = n - it * 7\n \n it += 1\n\n for i in range(mod):\n result += (i + it)\n \n return result\n```\n```C# []\npublic class Solution {\n public int TotalMoney(int n) {\n int result = 0;\n int it = n / 7;\n\n for (int i = 0; i < it; i++) {\n result += 28 + (i * 7);\n }\n\n int mod = n - it * 7;\n it += 1;\n\n for (int i = 0; i < mod; i++) {\n result += (i + it);\n }\n\n return result;\n }\n}\n```\n```Java []\npublic class Solution {\n public int totalMoney(int n) {\n int result = 0;\n int it = n / 7;\n \n for (int i = 0; i < it; i++) {\n result += 28 + (i * 7);\n }\n \n int mod = n - it * 7;\n it += 1;\n\n for (int i = 0; i < mod; i++) {\n result += (i + it);\n }\n\n return result;\n }\n}\n```\n``` Rust []\nimpl Solution {\n pub fn total_money(n: i32) -> i32 {\n let mut result = 0;\n let it = n / 7;\n\n for i in 0..it {\n result += 28 + (i * 7);\n }\n\n let mod_value = n - it * 7;\n let mut it = it + 1;\n\n for i in 0..mod_value {\n result += i + it;\n }\n\n result\n }\n}\n```\n![image name](https://i.imgur.com/JdL5kBI.gif)\n\n- Please upvote me !!!
7
You are given the logs for users' actions on LeetCode, and an integer `k`. The logs are represented by a 2D integer array `logs` where each `logs[i] = [IDi, timei]` indicates that the user with `IDi` performed an action at the minute `timei`. **Multiple users** can perform actions simultaneously, and a single user can perform **multiple actions** in the same minute. The **user active minutes (UAM)** for a given user is defined as the **number of unique minutes** in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it. You are to calculate a **1-indexed** array `answer` of size `k` such that, for each `j` (`1 <= j <= k`), `answer[j]` is the **number of users** whose **UAM** equals `j`. Return _the array_ `answer` _as described above_. **Example 1:** **Input:** logs = \[\[0,5\],\[1,2\],\[0,2\],\[0,5\],\[1,3\]\], k = 5 **Output:** \[0,2,0,0,0\] **Explanation:** The user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once). The user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. Since both users have a UAM of 2, answer\[2\] is 2, and the remaining answer\[j\] values are 0. **Example 2:** **Input:** logs = \[\[1,1\],\[2,2\],\[2,3\]\], k = 4 **Output:** \[1,1,0,0\] **Explanation:** The user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1. The user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. There is one user with a UAM of 1 and one with a UAM of 2. Hence, answer\[1\] = 1, answer\[2\] = 1, and the remaining values are 0. **Constraints:** * `1 <= logs.length <= 104` * `0 <= IDi <= 109` * `1 <= timei <= 105` * `k` is in the range `[The maximum **UAM** for a user, 105]`.
Simulate the process by keeping track of how much money John is putting in and which day of the week it is, and use this information to deduce how much money John will put in the next day.
✅ C/C++/Java/Rust/Python/C# - O(1) solution with two approaches | Beats 100 % | 0 ms time
calculate-money-in-leetcode-bank
1
1
### I solved this problem with two different approaches. In the first, I did what came to my mind first, and in the second one, I tried to optimize it.\n\n# 1st approach\n- Initialize sum and currentValue to zero and one, respectively.\n- Iterate from day 1 to day n.\n- On each day, add the currentValue to the sum.\n- If the current day is a multiple of 7, subtract 5 from currentValue to simulate the start of a new week; otherwise, increment currentValue.\n- Return the final sum.\n\n# Complexity\nI got O(n) where n is number of total days.\n\n# Code\nSo, this is the first solution.\n```C []\nint totalMoney(int n) {\n int sum = 0;\n int current_value = 1;\n for (int i = 1; i <= n; ++i) {\n sum += current_value;\n\n if (i % 7 == 0 && i != 0) {\n current_value -= 5;\n } else {\n current_value++;\n }\n }\n return sum;\n}\n```\n```C++ []\nint totalMoney(int n) {\n int sum = 0;\n int current_value = 1;\n for (int i = 1; i <= n; ++i) {\n sum += current_value;\n\n if (i % 7 == 0 && i != 0) {\n current_value -= 5;\n } else {\n current_value++;\n }\n }\n return sum;\n}\n```\n```C# []\npublic int TotalMoney(int n) {\n int sum = 0;\n int currentValue = 1;\n for(int i = 1; i <= n; i++)\n {\n sum += currentValue;\n\n if(i % 7 == 0 && i != 0)\n currentValue -= 5;\n else\n currentValue++; \n }\n \n return sum;\n}\n```\n```Rust []\nfn total_money(n: u32) -> u32 {\n let mut sum = 0;\n let mut current_value = 1;\n for i in 1..=n {\n sum += current_value;\n\n if i % 7 == 0 && i != 0 {\n current_value -= 5;\n } else {\n current_value += 1;\n }\n }\n sum\n}\n\n```\n```Java []\npublic class Solution {\n public int totalMoney(int n) {\n int sum = 0;\n int currentValue = 1;\n for (int i = 1; i <= n; i++) {\n sum += currentValue;\n\n if (i % 7 == 0 && i != 0) {\n currentValue -= 5;\n } else {\n currentValue++;\n }\n }\n return sum;\n }\n}\n```\n```Python []\ndef total_money(n):\n sum = 0\n current_value = 1\n for i in range(1, n + 1):\n sum += current_value\n\n if i % 7 == 0 and i != 0:\n current_value -= 5\n else:\n current_value += 1\n\n return sum\n\n```\n\n### Then I did some googling and found a better approach. \n# 2nd approach\n- Calculate the number of full weeks (weeks = n / 7) and the number of remaining days (remainingDays = n % 7).\n- Calculate the sum for full weeks using the arithmetic progression formula.\n- Add the sum for the remaining days, considering the starting value as the last value of the last week.\n- Return the final sum.\n# Complexity\nWe got O(1) here, guys.\n- Time: I got 0 ms in C, C++ and Rust which beats 100 % other solutions and 17 ms in C#\n- Space: I got 2 MB in Rust beating 93 % of the solutions and a bit more in other languages.\n![image_2023-12-07_11-49-23.png](https://assets.leetcode.com/users/images/b7bb560a-65a3-4caf-99f6-15bbed9e0422_1701932795.7110639.png)\n\n# Code - Final solution\n\n```C []\nint totalMoney(int n) {\n int weeks = n / 7;\n int remaining_days = n % 7;\n\n // Calculate the sum of full weeks\n int sum = 28 * weeks + 7 * (weeks - 1) * weeks / 2;\n\n // Add the sum of remaining days\n sum += remaining_days * (remaining_days + 1) / 2 + weeks * remaining_days;\n\n return sum;\n}\n\n```\n```C++ []\nint totalMoney(int n) {\n int weeks = n / 7;\n int remaining_days = n % 7;\n\n // Calculate the sum of full weeks\n int sum = 28 * weeks + 7 * (weeks - 1) * weeks / 2;\n\n // Add the sum of remaining days\n sum += remaining_days * (remaining_days + 1) / 2 + weeks * remaining_days;\n\n return sum;\n}\n```\n```C# []\npublic class Solution {\n public int TotalMoney(int n) {\n int weeks = n / 7;\n int remainingDays = n % 7;\n \n // Calculate the sum of full weeks\n int sum = 28 * weeks + 7 * (weeks - 1) * weeks / 2;\n \n // Add the sum of remaining days\n sum += remainingDays * (remainingDays + 1) / 2 + weeks * remainingDays;\n \n return sum;\n }\n}\n\n```\n```Rust []\nimpl Solution {\n pub fn total_money(n: i32) -> i32 {\n let weeks = n / 7;\n let remaining_days = n % 7;\n\n // Calculate the sum of full weeks\n let sum = 28 * weeks + 7 * (weeks - 1) * weeks / 2;\n\n // Add the sum of remaining days\n sum + remaining_days * (remaining_days + 1) / 2 + weeks * remaining_days\n }\n}\n```\n```Python []\ndef total_money(n):\n weeks = n // 7\n remaining_days = n % 7\n\n # Calculate the sum of full weeks\n sum = 28 * weeks + 7 * (weeks - 1) * weeks // 2\n\n # Add the sum of remaining days\n sum += remaining_days * (remaining_days + 1) // 2 + weeks * remaining_days\n\n return sum\n\n```\n```Java []\npublic class Solution {\n public int totalMoney(int n) {\n int weeks = n / 7;\n int remainingDays = n % 7;\n\n // Calculate the sum of full weeks\n int sum = 28 * weeks + 7 * (weeks - 1) * weeks / 2;\n\n // Add the sum of remaining days\n sum += remainingDays * (remainingDays + 1) / 2 + weeks * remainingDays;\n\n return sum;\n }\n}\n\n```\n\n![Now, you have to upvote!.png](https://assets.leetcode.com/users/images/569a6325-530e-4623-a3da-69ce0e1a4876_1701933707.8112352.png)\n## Upvote to keep me motivated! Don\'t stop the hard work!\n
5
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**. He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put 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:** * `1 <= n <= 1000`
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
✅ C/C++/Java/Rust/Python/C# - O(1) solution with two approaches | Beats 100 % | 0 ms time
calculate-money-in-leetcode-bank
1
1
### I solved this problem with two different approaches. In the first, I did what came to my mind first, and in the second one, I tried to optimize it.\n\n# 1st approach\n- Initialize sum and currentValue to zero and one, respectively.\n- Iterate from day 1 to day n.\n- On each day, add the currentValue to the sum.\n- If the current day is a multiple of 7, subtract 5 from currentValue to simulate the start of a new week; otherwise, increment currentValue.\n- Return the final sum.\n\n# Complexity\nI got O(n) where n is number of total days.\n\n# Code\nSo, this is the first solution.\n```C []\nint totalMoney(int n) {\n int sum = 0;\n int current_value = 1;\n for (int i = 1; i <= n; ++i) {\n sum += current_value;\n\n if (i % 7 == 0 && i != 0) {\n current_value -= 5;\n } else {\n current_value++;\n }\n }\n return sum;\n}\n```\n```C++ []\nint totalMoney(int n) {\n int sum = 0;\n int current_value = 1;\n for (int i = 1; i <= n; ++i) {\n sum += current_value;\n\n if (i % 7 == 0 && i != 0) {\n current_value -= 5;\n } else {\n current_value++;\n }\n }\n return sum;\n}\n```\n```C# []\npublic int TotalMoney(int n) {\n int sum = 0;\n int currentValue = 1;\n for(int i = 1; i <= n; i++)\n {\n sum += currentValue;\n\n if(i % 7 == 0 && i != 0)\n currentValue -= 5;\n else\n currentValue++; \n }\n \n return sum;\n}\n```\n```Rust []\nfn total_money(n: u32) -> u32 {\n let mut sum = 0;\n let mut current_value = 1;\n for i in 1..=n {\n sum += current_value;\n\n if i % 7 == 0 && i != 0 {\n current_value -= 5;\n } else {\n current_value += 1;\n }\n }\n sum\n}\n\n```\n```Java []\npublic class Solution {\n public int totalMoney(int n) {\n int sum = 0;\n int currentValue = 1;\n for (int i = 1; i <= n; i++) {\n sum += currentValue;\n\n if (i % 7 == 0 && i != 0) {\n currentValue -= 5;\n } else {\n currentValue++;\n }\n }\n return sum;\n }\n}\n```\n```Python []\ndef total_money(n):\n sum = 0\n current_value = 1\n for i in range(1, n + 1):\n sum += current_value\n\n if i % 7 == 0 and i != 0:\n current_value -= 5\n else:\n current_value += 1\n\n return sum\n\n```\n\n### Then I did some googling and found a better approach. \n# 2nd approach\n- Calculate the number of full weeks (weeks = n / 7) and the number of remaining days (remainingDays = n % 7).\n- Calculate the sum for full weeks using the arithmetic progression formula.\n- Add the sum for the remaining days, considering the starting value as the last value of the last week.\n- Return the final sum.\n# Complexity\nWe got O(1) here, guys.\n- Time: I got 0 ms in C, C++ and Rust which beats 100 % other solutions and 17 ms in C#\n- Space: I got 2 MB in Rust beating 93 % of the solutions and a bit more in other languages.\n![image_2023-12-07_11-49-23.png](https://assets.leetcode.com/users/images/b7bb560a-65a3-4caf-99f6-15bbed9e0422_1701932795.7110639.png)\n\n# Code - Final solution\n\n```C []\nint totalMoney(int n) {\n int weeks = n / 7;\n int remaining_days = n % 7;\n\n // Calculate the sum of full weeks\n int sum = 28 * weeks + 7 * (weeks - 1) * weeks / 2;\n\n // Add the sum of remaining days\n sum += remaining_days * (remaining_days + 1) / 2 + weeks * remaining_days;\n\n return sum;\n}\n\n```\n```C++ []\nint totalMoney(int n) {\n int weeks = n / 7;\n int remaining_days = n % 7;\n\n // Calculate the sum of full weeks\n int sum = 28 * weeks + 7 * (weeks - 1) * weeks / 2;\n\n // Add the sum of remaining days\n sum += remaining_days * (remaining_days + 1) / 2 + weeks * remaining_days;\n\n return sum;\n}\n```\n```C# []\npublic class Solution {\n public int TotalMoney(int n) {\n int weeks = n / 7;\n int remainingDays = n % 7;\n \n // Calculate the sum of full weeks\n int sum = 28 * weeks + 7 * (weeks - 1) * weeks / 2;\n \n // Add the sum of remaining days\n sum += remainingDays * (remainingDays + 1) / 2 + weeks * remainingDays;\n \n return sum;\n }\n}\n\n```\n```Rust []\nimpl Solution {\n pub fn total_money(n: i32) -> i32 {\n let weeks = n / 7;\n let remaining_days = n % 7;\n\n // Calculate the sum of full weeks\n let sum = 28 * weeks + 7 * (weeks - 1) * weeks / 2;\n\n // Add the sum of remaining days\n sum + remaining_days * (remaining_days + 1) / 2 + weeks * remaining_days\n }\n}\n```\n```Python []\ndef total_money(n):\n weeks = n // 7\n remaining_days = n % 7\n\n # Calculate the sum of full weeks\n sum = 28 * weeks + 7 * (weeks - 1) * weeks // 2\n\n # Add the sum of remaining days\n sum += remaining_days * (remaining_days + 1) // 2 + weeks * remaining_days\n\n return sum\n\n```\n```Java []\npublic class Solution {\n public int totalMoney(int n) {\n int weeks = n / 7;\n int remainingDays = n % 7;\n\n // Calculate the sum of full weeks\n int sum = 28 * weeks + 7 * (weeks - 1) * weeks / 2;\n\n // Add the sum of remaining days\n sum += remainingDays * (remainingDays + 1) / 2 + weeks * remainingDays;\n\n return sum;\n }\n}\n\n```\n\n![Now, you have to upvote!.png](https://assets.leetcode.com/users/images/569a6325-530e-4623-a3da-69ce0e1a4876_1701933707.8112352.png)\n## Upvote to keep me motivated! Don\'t stop the hard work!\n
5
You are given the logs for users' actions on LeetCode, and an integer `k`. The logs are represented by a 2D integer array `logs` where each `logs[i] = [IDi, timei]` indicates that the user with `IDi` performed an action at the minute `timei`. **Multiple users** can perform actions simultaneously, and a single user can perform **multiple actions** in the same minute. The **user active minutes (UAM)** for a given user is defined as the **number of unique minutes** in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it. You are to calculate a **1-indexed** array `answer` of size `k` such that, for each `j` (`1 <= j <= k`), `answer[j]` is the **number of users** whose **UAM** equals `j`. Return _the array_ `answer` _as described above_. **Example 1:** **Input:** logs = \[\[0,5\],\[1,2\],\[0,2\],\[0,5\],\[1,3\]\], k = 5 **Output:** \[0,2,0,0,0\] **Explanation:** The user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once). The user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. Since both users have a UAM of 2, answer\[2\] is 2, and the remaining answer\[j\] values are 0. **Example 2:** **Input:** logs = \[\[1,1\],\[2,2\],\[2,3\]\], k = 4 **Output:** \[1,1,0,0\] **Explanation:** The user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1. The user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. There is one user with a UAM of 1 and one with a UAM of 2. Hence, answer\[1\] = 1, answer\[2\] = 1, and the remaining values are 0. **Constraints:** * `1 <= logs.length <= 104` * `0 <= IDi <= 109` * `1 <= timei <= 105` * `k` is in the range `[The maximum **UAM** for a user, 105]`.
Simulate the process by keeping track of how much money John is putting in and which day of the week it is, and use this information to deduce how much money John will put in the next day.
Python3 Solution
calculate-money-in-leetcode-bank
0
1
\n```\nclass Solution:\n def totalMoney(self, n: int) -> int:\n ans=0\n offset=0\n for i in range(1,n+1):\n res=i%7\n if res%7==0:\n res+=7\n ans+=offset+res\n if i%7==0:\n offset+=1\n return ans \n```
4
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**. He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put 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:** * `1 <= n <= 1000`
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
Python3 Solution
calculate-money-in-leetcode-bank
0
1
\n```\nclass Solution:\n def totalMoney(self, n: int) -> int:\n ans=0\n offset=0\n for i in range(1,n+1):\n res=i%7\n if res%7==0:\n res+=7\n ans+=offset+res\n if i%7==0:\n offset+=1\n return ans \n```
4
You are given the logs for users' actions on LeetCode, and an integer `k`. The logs are represented by a 2D integer array `logs` where each `logs[i] = [IDi, timei]` indicates that the user with `IDi` performed an action at the minute `timei`. **Multiple users** can perform actions simultaneously, and a single user can perform **multiple actions** in the same minute. The **user active minutes (UAM)** for a given user is defined as the **number of unique minutes** in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it. You are to calculate a **1-indexed** array `answer` of size `k` such that, for each `j` (`1 <= j <= k`), `answer[j]` is the **number of users** whose **UAM** equals `j`. Return _the array_ `answer` _as described above_. **Example 1:** **Input:** logs = \[\[0,5\],\[1,2\],\[0,2\],\[0,5\],\[1,3\]\], k = 5 **Output:** \[0,2,0,0,0\] **Explanation:** The user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once). The user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. Since both users have a UAM of 2, answer\[2\] is 2, and the remaining answer\[j\] values are 0. **Example 2:** **Input:** logs = \[\[1,1\],\[2,2\],\[2,3\]\], k = 4 **Output:** \[1,1,0,0\] **Explanation:** The user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1. The user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. There is one user with a UAM of 1 and one with a UAM of 2. Hence, answer\[1\] = 1, answer\[2\] = 1, and the remaining values are 0. **Constraints:** * `1 <= logs.length <= 104` * `0 <= IDi <= 109` * `1 <= timei <= 105` * `k` is in the range `[The maximum **UAM** for a user, 105]`.
Simulate the process by keeping track of how much money John is putting in and which day of the week it is, and use this information to deduce how much money John will put in the next day.
Python Solution for beginners
calculate-money-in-leetcode-bank
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nEasy approach\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Initialize variables: n is set to 20 (the number of integers to sum), res is the result initialized to 0, i is a counter starting at 1, j is a loop counter starting at 0, and count is a variable to keep track of the group of consecutive numbers to skip (starts at 1).\n\n- Enter a while loop that continues until j reaches the target count of n.\n\n- Inside the loop, add the current value of i to the result res.\n\n- Check if i is equal to 7 + count - 1. If true, it means that i has reached the end of a group of consecutive numbers to skip. In that case, increment the count and set i to the value of count.\n\n- If the condition in step 4 is false, increment i by 1.\n\n- Increment the loop counter j by 1.\n\n- Repeat the loop until j reaches the target count of n.\n\n- Print the final result res, which is the sum of the specified positive integers while skipping consecutive numbers in groups of seven.\n\n\n\n\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def totalMoney(self, n: int) -> int:\n res=0\n i=1\n j=0\n count=1\n while j<n:\n \n res+=i\n if i==7+count-1:\n count+=1\n i=count\n else:\n i+=1\n j+=1\n \n \n \n \n return(res)\n \n```
2
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**. He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put 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:** * `1 <= n <= 1000`
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
Python Solution for beginners
calculate-money-in-leetcode-bank
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nEasy approach\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Initialize variables: n is set to 20 (the number of integers to sum), res is the result initialized to 0, i is a counter starting at 1, j is a loop counter starting at 0, and count is a variable to keep track of the group of consecutive numbers to skip (starts at 1).\n\n- Enter a while loop that continues until j reaches the target count of n.\n\n- Inside the loop, add the current value of i to the result res.\n\n- Check if i is equal to 7 + count - 1. If true, it means that i has reached the end of a group of consecutive numbers to skip. In that case, increment the count and set i to the value of count.\n\n- If the condition in step 4 is false, increment i by 1.\n\n- Increment the loop counter j by 1.\n\n- Repeat the loop until j reaches the target count of n.\n\n- Print the final result res, which is the sum of the specified positive integers while skipping consecutive numbers in groups of seven.\n\n\n\n\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def totalMoney(self, n: int) -> int:\n res=0\n i=1\n j=0\n count=1\n while j<n:\n \n res+=i\n if i==7+count-1:\n count+=1\n i=count\n else:\n i+=1\n j+=1\n \n \n \n \n return(res)\n \n```
2
You are given the logs for users' actions on LeetCode, and an integer `k`. The logs are represented by a 2D integer array `logs` where each `logs[i] = [IDi, timei]` indicates that the user with `IDi` performed an action at the minute `timei`. **Multiple users** can perform actions simultaneously, and a single user can perform **multiple actions** in the same minute. The **user active minutes (UAM)** for a given user is defined as the **number of unique minutes** in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it. You are to calculate a **1-indexed** array `answer` of size `k` such that, for each `j` (`1 <= j <= k`), `answer[j]` is the **number of users** whose **UAM** equals `j`. Return _the array_ `answer` _as described above_. **Example 1:** **Input:** logs = \[\[0,5\],\[1,2\],\[0,2\],\[0,5\],\[1,3\]\], k = 5 **Output:** \[0,2,0,0,0\] **Explanation:** The user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once). The user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. Since both users have a UAM of 2, answer\[2\] is 2, and the remaining answer\[j\] values are 0. **Example 2:** **Input:** logs = \[\[1,1\],\[2,2\],\[2,3\]\], k = 4 **Output:** \[1,1,0,0\] **Explanation:** The user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1. The user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. There is one user with a UAM of 1 and one with a UAM of 2. Hence, answer\[1\] = 1, answer\[2\] = 1, and the remaining values are 0. **Constraints:** * `1 <= logs.length <= 104` * `0 <= IDi <= 109` * `1 <= timei <= 105` * `k` is in the range `[The maximum **UAM** for a user, 105]`.
Simulate the process by keeping track of how much money John is putting in and which day of the week it is, and use this information to deduce how much money John will put in the next day.
O(1) Formula solution
calculate-money-in-leetcode-bank
0
1
# Approach\n\nFirst week we put `28` dollars.\nNext week we put `28 + 7` dollars.\nThen we put `28 + 7 + 7` dollars and so on...\n\nThe formula for $m^{th}$ week is $28 + 7*(m-1)$.\n\nUsing arithmetic progression sum formula $\\frac{2a_1+t(m-1)}{2}*m$, we can find the sum of `n` weeks.\n\n`a_1` is `28`\n`t` is `7`\n`m` is `n // 7`\n\nThe sum of `n` weeks is `(n // 7) * (2 * 28 + 7 * (n // 7 - 1)) // 2`.\n\nWhat about the remainder?\n\nAfter `n // 7` we have `n % 7` days. \n\nFor the first week we get `1 + 2 + 3 + 4`. \nFor the second week we get `1 + 2 + 3 + 4 + (4)`.\nFor the third week we get `1 + 2 + 3 + 4 + (8)` and so on.\n\nWe can use arithmetic progression sum formula again.\n\nBase case is `(n % 7) * (n % 7 + 1) // 2`. Then add `(n // 7) * (n % 7)`.\n\nLet\'s define `d` as `n // 7` and `r` as `n % 7`.\n\nSo the result formula is \n\n```python\nd * (2 * 28 + 7 * (d - 1)) // 2 + r * (r + 1) // 2 + d * r\n```\n\n# Complexity\n- Time complexity: $$O(1)$$\n- Space complexity: $$O(1)$$\n\n# Code\n```python\nclass Solution:\n def totalMoney(self, n: int) -> int:\n d, r = divmod(n, 7)\n return d * (2 * 28 + 7 * (d - 1)) // 2 + r * (r + 1) // 2 + d * r\n\n```
2
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**. He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put 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:** * `1 <= n <= 1000`
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
O(1) Formula solution
calculate-money-in-leetcode-bank
0
1
# Approach\n\nFirst week we put `28` dollars.\nNext week we put `28 + 7` dollars.\nThen we put `28 + 7 + 7` dollars and so on...\n\nThe formula for $m^{th}$ week is $28 + 7*(m-1)$.\n\nUsing arithmetic progression sum formula $\\frac{2a_1+t(m-1)}{2}*m$, we can find the sum of `n` weeks.\n\n`a_1` is `28`\n`t` is `7`\n`m` is `n // 7`\n\nThe sum of `n` weeks is `(n // 7) * (2 * 28 + 7 * (n // 7 - 1)) // 2`.\n\nWhat about the remainder?\n\nAfter `n // 7` we have `n % 7` days. \n\nFor the first week we get `1 + 2 + 3 + 4`. \nFor the second week we get `1 + 2 + 3 + 4 + (4)`.\nFor the third week we get `1 + 2 + 3 + 4 + (8)` and so on.\n\nWe can use arithmetic progression sum formula again.\n\nBase case is `(n % 7) * (n % 7 + 1) // 2`. Then add `(n // 7) * (n % 7)`.\n\nLet\'s define `d` as `n // 7` and `r` as `n % 7`.\n\nSo the result formula is \n\n```python\nd * (2 * 28 + 7 * (d - 1)) // 2 + r * (r + 1) // 2 + d * r\n```\n\n# Complexity\n- Time complexity: $$O(1)$$\n- Space complexity: $$O(1)$$\n\n# Code\n```python\nclass Solution:\n def totalMoney(self, n: int) -> int:\n d, r = divmod(n, 7)\n return d * (2 * 28 + 7 * (d - 1)) // 2 + r * (r + 1) // 2 + d * r\n\n```
2
You are given the logs for users' actions on LeetCode, and an integer `k`. The logs are represented by a 2D integer array `logs` where each `logs[i] = [IDi, timei]` indicates that the user with `IDi` performed an action at the minute `timei`. **Multiple users** can perform actions simultaneously, and a single user can perform **multiple actions** in the same minute. The **user active minutes (UAM)** for a given user is defined as the **number of unique minutes** in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it. You are to calculate a **1-indexed** array `answer` of size `k` such that, for each `j` (`1 <= j <= k`), `answer[j]` is the **number of users** whose **UAM** equals `j`. Return _the array_ `answer` _as described above_. **Example 1:** **Input:** logs = \[\[0,5\],\[1,2\],\[0,2\],\[0,5\],\[1,3\]\], k = 5 **Output:** \[0,2,0,0,0\] **Explanation:** The user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once). The user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. Since both users have a UAM of 2, answer\[2\] is 2, and the remaining answer\[j\] values are 0. **Example 2:** **Input:** logs = \[\[1,1\],\[2,2\],\[2,3\]\], k = 4 **Output:** \[1,1,0,0\] **Explanation:** The user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1. The user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. There is one user with a UAM of 1 and one with a UAM of 2. Hence, answer\[1\] = 1, answer\[2\] = 1, and the remaining values are 0. **Constraints:** * `1 <= logs.length <= 104` * `0 <= IDi <= 109` * `1 <= timei <= 105` * `k` is in the range `[The maximum **UAM** for a user, 105]`.
Simulate the process by keeping track of how much money John is putting in and which day of the week it is, and use this information to deduce how much money John will put in the next day.
Rust/Python constant time solution with explanation
calculate-money-in-leetcode-bank
0
1
# Intuition\n\nOf course you can just simulate it, but it will take linear time. You can do better by using math.\n\nFirst lets look at whole weeks 7, 14, 21 and so on days. First day week consumes `1 + 2 + ... + 7 = 28`. Next day will be `2 + 3 + ... + 8 = (1 + 2 + ... + 7) + 7`. For i-th week (starts with 0th week) the sum will be `28 + 7 * i`. And you can calculate the sum of first `x` weeks as `28 * x + 7 * x * (x - 1) / 2`.\n\nAs at most you will have additional at most 7 days. You can also caclulate it but with just 7 values you can simulate them. So here is a full solution\n\n# Complexity\n- Time complexity: $O(1)$\n- Space complexity: $O(1)$\n\n# Code\n```Rust []\nimpl Solution {\n pub fn total_money(n: i32) -> i32 {\n let x = n / 7;\n let mut res = 28 * x + 7 * x * (x - 1) / 2;\n\n let m = n % 7;\n for i in 1 ..=m {\n res += x + i;\n }\n\n return res;\n }\n}\n```\n```python []\nclass Solution:\n def totalMoney(self, n: int) -> int:\n x = n // 7\n res = 28 * x + 7 * x * (x - 1) // 2\n\n for i in range(1, n % 7 + 1):\n res += x + i\n \n return res\n```
2
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**. He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put 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:** * `1 <= n <= 1000`
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
Rust/Python constant time solution with explanation
calculate-money-in-leetcode-bank
0
1
# Intuition\n\nOf course you can just simulate it, but it will take linear time. You can do better by using math.\n\nFirst lets look at whole weeks 7, 14, 21 and so on days. First day week consumes `1 + 2 + ... + 7 = 28`. Next day will be `2 + 3 + ... + 8 = (1 + 2 + ... + 7) + 7`. For i-th week (starts with 0th week) the sum will be `28 + 7 * i`. And you can calculate the sum of first `x` weeks as `28 * x + 7 * x * (x - 1) / 2`.\n\nAs at most you will have additional at most 7 days. You can also caclulate it but with just 7 values you can simulate them. So here is a full solution\n\n# Complexity\n- Time complexity: $O(1)$\n- Space complexity: $O(1)$\n\n# Code\n```Rust []\nimpl Solution {\n pub fn total_money(n: i32) -> i32 {\n let x = n / 7;\n let mut res = 28 * x + 7 * x * (x - 1) / 2;\n\n let m = n % 7;\n for i in 1 ..=m {\n res += x + i;\n }\n\n return res;\n }\n}\n```\n```python []\nclass Solution:\n def totalMoney(self, n: int) -> int:\n x = n // 7\n res = 28 * x + 7 * x * (x - 1) // 2\n\n for i in range(1, n % 7 + 1):\n res += x + i\n \n return res\n```
2
You are given the logs for users' actions on LeetCode, and an integer `k`. The logs are represented by a 2D integer array `logs` where each `logs[i] = [IDi, timei]` indicates that the user with `IDi` performed an action at the minute `timei`. **Multiple users** can perform actions simultaneously, and a single user can perform **multiple actions** in the same minute. The **user active minutes (UAM)** for a given user is defined as the **number of unique minutes** in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it. You are to calculate a **1-indexed** array `answer` of size `k` such that, for each `j` (`1 <= j <= k`), `answer[j]` is the **number of users** whose **UAM** equals `j`. Return _the array_ `answer` _as described above_. **Example 1:** **Input:** logs = \[\[0,5\],\[1,2\],\[0,2\],\[0,5\],\[1,3\]\], k = 5 **Output:** \[0,2,0,0,0\] **Explanation:** The user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once). The user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. Since both users have a UAM of 2, answer\[2\] is 2, and the remaining answer\[j\] values are 0. **Example 2:** **Input:** logs = \[\[1,1\],\[2,2\],\[2,3\]\], k = 4 **Output:** \[1,1,0,0\] **Explanation:** The user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1. The user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. There is one user with a UAM of 1 and one with a UAM of 2. Hence, answer\[1\] = 1, answer\[2\] = 1, and the remaining values are 0. **Constraints:** * `1 <= logs.length <= 104` * `0 <= IDi <= 109` * `1 <= timei <= 105` * `k` is in the range `[The maximum **UAM** for a user, 105]`.
Simulate the process by keeping track of how much money John is putting in and which day of the week it is, and use this information to deduce how much money John will put in the next day.
🔥🔥 Simplest Code | 2ms | For Beginners | Fully Explained 🚀🔥
calculate-money-in-leetcode-bank
1
1
# Intuition\n![lc1.png](https://assets.leetcode.com/users/images/562ac1c2-3b37-44f7-bb95-36e99669bb9c_1701826680.2613792.png)\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n - Initialize `ans` to 0 for aggregating savings and `mon` to 1 for the current Monday\'s deposit. \uD83C\uDF1F\n- Utilize a `while` loop until the specified number of days, `n`, reaches 0. \uD83D\uDD04\n- Inside the loop, check if `n` is greater than or equal to 7.\n - If true, iterate over a week (7 days) from `mon` to `mon + 7`, adding each day\'s deposit to `ans`. \uD83D\uDCBC\n - Increment `mon` by 1 for the next Monday. \uD83D\uDCC8\n - Subtract 7 from `n` to account for a week. \uD83D\uDDD3\uFE0F\n- If `n` is less than 7, iterate over the remaining days from `mon` to `mon + n`, adding each day\'s deposit to `ans`. \uD83D\uDCC5\n- Set `n` to 0 to exit the loop. \uD83D\uDED1\n- Return the final value of `ans`, reflecting Hercy\'s total savings. \uD83D\uDCCA\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int totalMoney(int n) {\n ios_base::sync_with_stdio(false);\n cin.tie(0);\n cout.tie(0);\n \n int ans = 0;\n int mon = 1;\n\n while(n > 0)\n {\n if(n >= 7)\n {\n for(long i = mon; i < mon + 7; i++) ans += i;\n mon++;\n n = n - 7;\n }\n else\n {\n for(long i = mon; i < mon + n; i++) ans += i;\n n = 0;\n }\n }\n return ans;\n }\n};\n```\n![lc.gif](https://assets.leetcode.com/users/images/e60d360c-16f5-4b91-93ba-c717c948093e_1701826668.992975.gif)\n
11
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**. He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put 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:** * `1 <= n <= 1000`
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
🔥🔥 Simplest Code | 2ms | For Beginners | Fully Explained 🚀🔥
calculate-money-in-leetcode-bank
1
1
# Intuition\n![lc1.png](https://assets.leetcode.com/users/images/562ac1c2-3b37-44f7-bb95-36e99669bb9c_1701826680.2613792.png)\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n - Initialize `ans` to 0 for aggregating savings and `mon` to 1 for the current Monday\'s deposit. \uD83C\uDF1F\n- Utilize a `while` loop until the specified number of days, `n`, reaches 0. \uD83D\uDD04\n- Inside the loop, check if `n` is greater than or equal to 7.\n - If true, iterate over a week (7 days) from `mon` to `mon + 7`, adding each day\'s deposit to `ans`. \uD83D\uDCBC\n - Increment `mon` by 1 for the next Monday. \uD83D\uDCC8\n - Subtract 7 from `n` to account for a week. \uD83D\uDDD3\uFE0F\n- If `n` is less than 7, iterate over the remaining days from `mon` to `mon + n`, adding each day\'s deposit to `ans`. \uD83D\uDCC5\n- Set `n` to 0 to exit the loop. \uD83D\uDED1\n- Return the final value of `ans`, reflecting Hercy\'s total savings. \uD83D\uDCCA\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int totalMoney(int n) {\n ios_base::sync_with_stdio(false);\n cin.tie(0);\n cout.tie(0);\n \n int ans = 0;\n int mon = 1;\n\n while(n > 0)\n {\n if(n >= 7)\n {\n for(long i = mon; i < mon + 7; i++) ans += i;\n mon++;\n n = n - 7;\n }\n else\n {\n for(long i = mon; i < mon + n; i++) ans += i;\n n = 0;\n }\n }\n return ans;\n }\n};\n```\n![lc.gif](https://assets.leetcode.com/users/images/e60d360c-16f5-4b91-93ba-c717c948093e_1701826668.992975.gif)\n
11
You are given the logs for users' actions on LeetCode, and an integer `k`. The logs are represented by a 2D integer array `logs` where each `logs[i] = [IDi, timei]` indicates that the user with `IDi` performed an action at the minute `timei`. **Multiple users** can perform actions simultaneously, and a single user can perform **multiple actions** in the same minute. The **user active minutes (UAM)** for a given user is defined as the **number of unique minutes** in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it. You are to calculate a **1-indexed** array `answer` of size `k` such that, for each `j` (`1 <= j <= k`), `answer[j]` is the **number of users** whose **UAM** equals `j`. Return _the array_ `answer` _as described above_. **Example 1:** **Input:** logs = \[\[0,5\],\[1,2\],\[0,2\],\[0,5\],\[1,3\]\], k = 5 **Output:** \[0,2,0,0,0\] **Explanation:** The user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once). The user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. Since both users have a UAM of 2, answer\[2\] is 2, and the remaining answer\[j\] values are 0. **Example 2:** **Input:** logs = \[\[1,1\],\[2,2\],\[2,3\]\], k = 4 **Output:** \[1,1,0,0\] **Explanation:** The user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1. The user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. There is one user with a UAM of 1 and one with a UAM of 2. Hence, answer\[1\] = 1, answer\[2\] = 1, and the remaining values are 0. **Constraints:** * `1 <= logs.length <= 104` * `0 <= IDi <= 109` * `1 <= timei <= 105` * `k` is in the range `[The maximum **UAM** for a user, 105]`.
Simulate the process by keeping track of how much money John is putting in and which day of the week it is, and use this information to deduce how much money John will put in the next day.
Python3 / Rust integer division and remainder approach
calculate-money-in-leetcode-bank
0
1
# Intuition\nThe problem describes a scenario where Hercy saves money in the Leetcode bank. He starts with \\$1 on the first day (Monday) and adds an additional dollar each day. The pattern resets every Monday, with each Monday having $1 more than the previous Monday. The goal is to calculate the total amount of money Hercy will have at the end of the nth day.\n\n# Approach\nThe given solution divides the days into complete weeks and handles the remaining days separately.\n\n##### Complete Weeks:\n- The variable $whole$ represents the number of complete weeks in the given $n$ days, calculated by $n // 7$ (integer division).\n- The loop iterates over each complete week.\n- For each week, the amount of money earned is calculated and added to $total$.\n- The amount earned in each week follows a linear pattern: $7 * i + 28$.\n- The term $7 * i$ represents the extra money earned in each week.\nThe term $28$ represents the base amount earned in a week.\n\n##### Remaining Days:\n- The variable $remainder$ represents the number of remaining days after considering complete weeks, calculated by $n % 7$ (remainder of the division).\n- Another loop iterates over each remaining day.\n- For each remaining day, the amount of money earned is calculated and added to the $total$.\n- The amount earned in each remaining day follows a linear pattern: $whole + i + 1$.\n- The term $whole$ represents the additional amount earned for each remaining day based on the number of complete weeks.\n- The term $i + 1$ represents the linear increase in the amount earned for each remaining day.\n\n##### Return Total:\nThe $total$ is the sum of the money earned in complete weeks and the money earned in the remaining days.\n\n\n\n# Complexity\n- Time complexity: $O(n)$\n- Space complexity: $O(1)$\n\n# Code\n\n\n\n```python []\nclass Solution:\n def totalMoney(self, n: int) -> int:\n total = 0\n\n whole = n // 7\n remainder = n % 7\n\n for i in range(whole):\n total = total + 7 * i + 28\n \n for i in range(remainder):\n total = total + whole + i + 1\n \n return total\n```\n```rust []\nimpl Solution {\n pub fn total_money(n: i32) -> i32 {\n let mut total: i32 = 0;\n\n let whole: i32 = n / 7;\n let remainder: i32 = n % 7;\n\n for i in 0..whole {\n total += 7 * i + 28;\n }\n\n for i in whole..whole+remainder {\n total += i + 1;\n }\n\n total\n }\n}\n```
1
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**. He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put 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:** * `1 <= n <= 1000`
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
Python3 / Rust integer division and remainder approach
calculate-money-in-leetcode-bank
0
1
# Intuition\nThe problem describes a scenario where Hercy saves money in the Leetcode bank. He starts with \\$1 on the first day (Monday) and adds an additional dollar each day. The pattern resets every Monday, with each Monday having $1 more than the previous Monday. The goal is to calculate the total amount of money Hercy will have at the end of the nth day.\n\n# Approach\nThe given solution divides the days into complete weeks and handles the remaining days separately.\n\n##### Complete Weeks:\n- The variable $whole$ represents the number of complete weeks in the given $n$ days, calculated by $n // 7$ (integer division).\n- The loop iterates over each complete week.\n- For each week, the amount of money earned is calculated and added to $total$.\n- The amount earned in each week follows a linear pattern: $7 * i + 28$.\n- The term $7 * i$ represents the extra money earned in each week.\nThe term $28$ represents the base amount earned in a week.\n\n##### Remaining Days:\n- The variable $remainder$ represents the number of remaining days after considering complete weeks, calculated by $n % 7$ (remainder of the division).\n- Another loop iterates over each remaining day.\n- For each remaining day, the amount of money earned is calculated and added to the $total$.\n- The amount earned in each remaining day follows a linear pattern: $whole + i + 1$.\n- The term $whole$ represents the additional amount earned for each remaining day based on the number of complete weeks.\n- The term $i + 1$ represents the linear increase in the amount earned for each remaining day.\n\n##### Return Total:\nThe $total$ is the sum of the money earned in complete weeks and the money earned in the remaining days.\n\n\n\n# Complexity\n- Time complexity: $O(n)$\n- Space complexity: $O(1)$\n\n# Code\n\n\n\n```python []\nclass Solution:\n def totalMoney(self, n: int) -> int:\n total = 0\n\n whole = n // 7\n remainder = n % 7\n\n for i in range(whole):\n total = total + 7 * i + 28\n \n for i in range(remainder):\n total = total + whole + i + 1\n \n return total\n```\n```rust []\nimpl Solution {\n pub fn total_money(n: i32) -> i32 {\n let mut total: i32 = 0;\n\n let whole: i32 = n / 7;\n let remainder: i32 = n % 7;\n\n for i in 0..whole {\n total += 7 * i + 28;\n }\n\n for i in whole..whole+remainder {\n total += i + 1;\n }\n\n total\n }\n}\n```
1
You are given the logs for users' actions on LeetCode, and an integer `k`. The logs are represented by a 2D integer array `logs` where each `logs[i] = [IDi, timei]` indicates that the user with `IDi` performed an action at the minute `timei`. **Multiple users** can perform actions simultaneously, and a single user can perform **multiple actions** in the same minute. The **user active minutes (UAM)** for a given user is defined as the **number of unique minutes** in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it. You are to calculate a **1-indexed** array `answer` of size `k` such that, for each `j` (`1 <= j <= k`), `answer[j]` is the **number of users** whose **UAM** equals `j`. Return _the array_ `answer` _as described above_. **Example 1:** **Input:** logs = \[\[0,5\],\[1,2\],\[0,2\],\[0,5\],\[1,3\]\], k = 5 **Output:** \[0,2,0,0,0\] **Explanation:** The user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once). The user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. Since both users have a UAM of 2, answer\[2\] is 2, and the remaining answer\[j\] values are 0. **Example 2:** **Input:** logs = \[\[1,1\],\[2,2\],\[2,3\]\], k = 4 **Output:** \[1,1,0,0\] **Explanation:** The user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1. The user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. There is one user with a UAM of 1 and one with a UAM of 2. Hence, answer\[1\] = 1, answer\[2\] = 1, and the remaining values are 0. **Constraints:** * `1 <= logs.length <= 104` * `0 <= IDi <= 109` * `1 <= timei <= 105` * `k` is in the range `[The maximum **UAM** for a user, 105]`.
Simulate the process by keeping track of how much money John is putting in and which day of the week it is, and use this information to deduce how much money John will put in the next day.
✅ One Line Solution
calculate-money-in-leetcode-bank
0
1
# Code #1.1 - Oneliner\nTime complexity: $$O(1)$$. Space complexity: $$O(1)$$.\n```\nclass Solution:\n def totalMoney(self, n: int) -> int:\n return (s:=lambda a,d,k:(2*a+d*(k-1))*k//2) and (s(1,1,7)*(n//7) + s(0,7,n//7) + s(n//7+1,1,n%7))\n```\n\n# Code #1.2 - Unwrapped\n```\nclass Solution:\n def totalMoney(self, n: int) -> int:\n def summ(a, d, k):\n return (2*a + d*(k - 1))*k//2\n\n numOfWeeks = n//7\n numOfLastDays = n%7\n weekBaseSum = summ(1, 1, 7)*numOfWeeks\n weekRaiseSum = summ(0, 7, numOfWeeks)\n lastDaysSum = summ(numOfWeeks + 1, 1, numOfLastDays)\n \n return weekBaseSum + weekRaiseSum + lastDaysSum\n```\n\n# Code #2 - Simulation\nTime complexity: $$O(n)$$. Space complexity: $$O(1)$$.\n```\nclass Solution:\n def totalMoney(self, n: int) -> int:\n day = 0\n money = 0\n lot = 0\n while day < n:\n if day%7 == 0:\n lot = day//7 + 1\n else:\n lot += 1\n \n money += lot\n day += 1\n\n return money\n```
4
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**. He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put 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:** * `1 <= n <= 1000`
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
✅ One Line Solution
calculate-money-in-leetcode-bank
0
1
# Code #1.1 - Oneliner\nTime complexity: $$O(1)$$. Space complexity: $$O(1)$$.\n```\nclass Solution:\n def totalMoney(self, n: int) -> int:\n return (s:=lambda a,d,k:(2*a+d*(k-1))*k//2) and (s(1,1,7)*(n//7) + s(0,7,n//7) + s(n//7+1,1,n%7))\n```\n\n# Code #1.2 - Unwrapped\n```\nclass Solution:\n def totalMoney(self, n: int) -> int:\n def summ(a, d, k):\n return (2*a + d*(k - 1))*k//2\n\n numOfWeeks = n//7\n numOfLastDays = n%7\n weekBaseSum = summ(1, 1, 7)*numOfWeeks\n weekRaiseSum = summ(0, 7, numOfWeeks)\n lastDaysSum = summ(numOfWeeks + 1, 1, numOfLastDays)\n \n return weekBaseSum + weekRaiseSum + lastDaysSum\n```\n\n# Code #2 - Simulation\nTime complexity: $$O(n)$$. Space complexity: $$O(1)$$.\n```\nclass Solution:\n def totalMoney(self, n: int) -> int:\n day = 0\n money = 0\n lot = 0\n while day < n:\n if day%7 == 0:\n lot = day//7 + 1\n else:\n lot += 1\n \n money += lot\n day += 1\n\n return money\n```
4
You are given the logs for users' actions on LeetCode, and an integer `k`. The logs are represented by a 2D integer array `logs` where each `logs[i] = [IDi, timei]` indicates that the user with `IDi` performed an action at the minute `timei`. **Multiple users** can perform actions simultaneously, and a single user can perform **multiple actions** in the same minute. The **user active minutes (UAM)** for a given user is defined as the **number of unique minutes** in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it. You are to calculate a **1-indexed** array `answer` of size `k` such that, for each `j` (`1 <= j <= k`), `answer[j]` is the **number of users** whose **UAM** equals `j`. Return _the array_ `answer` _as described above_. **Example 1:** **Input:** logs = \[\[0,5\],\[1,2\],\[0,2\],\[0,5\],\[1,3\]\], k = 5 **Output:** \[0,2,0,0,0\] **Explanation:** The user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once). The user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. Since both users have a UAM of 2, answer\[2\] is 2, and the remaining answer\[j\] values are 0. **Example 2:** **Input:** logs = \[\[1,1\],\[2,2\],\[2,3\]\], k = 4 **Output:** \[1,1,0,0\] **Explanation:** The user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1. The user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. There is one user with a UAM of 1 and one with a UAM of 2. Hence, answer\[1\] = 1, answer\[2\] = 1, and the remaining values are 0. **Constraints:** * `1 <= logs.length <= 104` * `0 <= IDi <= 109` * `1 <= timei <= 105` * `k` is in the range `[The maximum **UAM** for a user, 105]`.
Simulate the process by keeping track of how much money John is putting in and which day of the week it is, and use this information to deduce how much money John will put in the next day.
Money in Leetcode bank.
calculate-money-in-leetcode-bank
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nKeen observation of the pattern of the numbers.\n\n\n# Complexity\n- Time complexity: O(1)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def totalMoney(self, n: int) -> int:\n if n > 7:\n count = n // 7 # to find the number of sets with 7 \n remaining = n % 7 # to find the remaning number of numbers without the 7 set\n if remaining!=0: # calculating the sum of the elements without 7 set\n middleSum = (((count+remaining)*(count+remaining+1))/2) - ((count)*(count+1)/2)\n else:\n middleSum = 0 # if set of 7 formed then there wont ne any extra numbers\n totalSum = count * 28 + ((count-1)*(count)/2) * 7 + middleSum # computing the final sum\n else:\n totalSum = (n*(n+1)/2) # if value of n lesser than 7 simply calculate the sum uptil that number\n\n return int(totalSum) # return the totalsum\n\n\n\n \n \n\n\n\n \n```
1
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**. He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put 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:** * `1 <= n <= 1000`
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
Money in Leetcode bank.
calculate-money-in-leetcode-bank
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nKeen observation of the pattern of the numbers.\n\n\n# Complexity\n- Time complexity: O(1)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def totalMoney(self, n: int) -> int:\n if n > 7:\n count = n // 7 # to find the number of sets with 7 \n remaining = n % 7 # to find the remaning number of numbers without the 7 set\n if remaining!=0: # calculating the sum of the elements without 7 set\n middleSum = (((count+remaining)*(count+remaining+1))/2) - ((count)*(count+1)/2)\n else:\n middleSum = 0 # if set of 7 formed then there wont ne any extra numbers\n totalSum = count * 28 + ((count-1)*(count)/2) * 7 + middleSum # computing the final sum\n else:\n totalSum = (n*(n+1)/2) # if value of n lesser than 7 simply calculate the sum uptil that number\n\n return int(totalSum) # return the totalsum\n\n\n\n \n \n\n\n\n \n```
1
You are given the logs for users' actions on LeetCode, and an integer `k`. The logs are represented by a 2D integer array `logs` where each `logs[i] = [IDi, timei]` indicates that the user with `IDi` performed an action at the minute `timei`. **Multiple users** can perform actions simultaneously, and a single user can perform **multiple actions** in the same minute. The **user active minutes (UAM)** for a given user is defined as the **number of unique minutes** in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it. You are to calculate a **1-indexed** array `answer` of size `k` such that, for each `j` (`1 <= j <= k`), `answer[j]` is the **number of users** whose **UAM** equals `j`. Return _the array_ `answer` _as described above_. **Example 1:** **Input:** logs = \[\[0,5\],\[1,2\],\[0,2\],\[0,5\],\[1,3\]\], k = 5 **Output:** \[0,2,0,0,0\] **Explanation:** The user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once). The user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. Since both users have a UAM of 2, answer\[2\] is 2, and the remaining answer\[j\] values are 0. **Example 2:** **Input:** logs = \[\[1,1\],\[2,2\],\[2,3\]\], k = 4 **Output:** \[1,1,0,0\] **Explanation:** The user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1. The user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. There is one user with a UAM of 1 and one with a UAM of 2. Hence, answer\[1\] = 1, answer\[2\] = 1, and the remaining values are 0. **Constraints:** * `1 <= logs.length <= 104` * `0 <= IDi <= 109` * `1 <= timei <= 105` * `k` is in the range `[The maximum **UAM** for a user, 105]`.
Simulate the process by keeping track of how much money John is putting in and which day of the week it is, and use this information to deduce how much money John will put in the next day.
calculateMoneyInLeetcodeBank
calculate-money-in-leetcode-bank
0
1
\n# Code\n```\n# time complexity: O(n)\nclass Solution:\n def totalMoney(self, n: int) -> int:\n count = 0 # value that gets added to the list\n end = 0 # value to keep track when the value of n becomes multiple of 7 (for every monday)\n start = 1 # to keep track of the value to be increased for each subsequent monday\n answerList = [] # list that contains the answer values\n for i in range(n):\n count = count + 1\n end = end + 1\n if end % 7 == 0:\n answerList.append(count)\n start = start + 1\n count = start - 1\n end = 0\n else:\n answerList.append(count)\n\n return sum(answerList)\n \n \n \n\n\n\n \n \n \n\n\n\n \n```
1
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**. He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put 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:** * `1 <= n <= 1000`
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
calculateMoneyInLeetcodeBank
calculate-money-in-leetcode-bank
0
1
\n# Code\n```\n# time complexity: O(n)\nclass Solution:\n def totalMoney(self, n: int) -> int:\n count = 0 # value that gets added to the list\n end = 0 # value to keep track when the value of n becomes multiple of 7 (for every monday)\n start = 1 # to keep track of the value to be increased for each subsequent monday\n answerList = [] # list that contains the answer values\n for i in range(n):\n count = count + 1\n end = end + 1\n if end % 7 == 0:\n answerList.append(count)\n start = start + 1\n count = start - 1\n end = 0\n else:\n answerList.append(count)\n\n return sum(answerList)\n \n \n \n\n\n\n \n \n \n\n\n\n \n```
1
You are given the logs for users' actions on LeetCode, and an integer `k`. The logs are represented by a 2D integer array `logs` where each `logs[i] = [IDi, timei]` indicates that the user with `IDi` performed an action at the minute `timei`. **Multiple users** can perform actions simultaneously, and a single user can perform **multiple actions** in the same minute. The **user active minutes (UAM)** for a given user is defined as the **number of unique minutes** in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it. You are to calculate a **1-indexed** array `answer` of size `k` such that, for each `j` (`1 <= j <= k`), `answer[j]` is the **number of users** whose **UAM** equals `j`. Return _the array_ `answer` _as described above_. **Example 1:** **Input:** logs = \[\[0,5\],\[1,2\],\[0,2\],\[0,5\],\[1,3\]\], k = 5 **Output:** \[0,2,0,0,0\] **Explanation:** The user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once). The user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. Since both users have a UAM of 2, answer\[2\] is 2, and the remaining answer\[j\] values are 0. **Example 2:** **Input:** logs = \[\[1,1\],\[2,2\],\[2,3\]\], k = 4 **Output:** \[1,1,0,0\] **Explanation:** The user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1. The user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. There is one user with a UAM of 1 and one with a UAM of 2. Hence, answer\[1\] = 1, answer\[2\] = 1, and the remaining values are 0. **Constraints:** * `1 <= logs.length <= 104` * `0 <= IDi <= 109` * `1 <= timei <= 105` * `k` is in the range `[The maximum **UAM** for a user, 105]`.
Simulate the process by keeping track of how much money John is putting in and which day of the week it is, and use this information to deduce how much money John will put in the next day.
Mathematical Approach | T.C. - O(1) | Beginner Friendly | Explanation - [Video] | Easy Solution
calculate-money-in-leetcode-bank
0
1
For better understanding of the question you can also check out this video. Hope it helps.\n\nhttps://youtu.be/3Pjay2_v-os\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n1. **Contribution from complete weeks:** The code calculates the total contribution from complete weeks using the formula for the sum of the first `n` natural numbers. The total contribution is then multiplied by 7 to account for each day in a week.\n\n2. **Contribution from remaining days:** The code calculates the sum of an arithmetic series for the remaining days, including the additional contributions on Mondays. This contribution is added to the total.\n\n3. **Final Total:** The total contributions from complete weeks and remaining days are added together to get the final total amount Hercy puts in the bank.\n\nPlease subscribe to my channel if it helped you.\nhttps://www.youtube.com/channel/UCsu5CDZmlHcpH7dQozZWtQw?sub_confirmation=1\n\nCurrent subscribers: 213\nTarget subscribers: 250\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Complete Weeks Contribution:**\n - The code first calculates the number of complete weeks (`week`) and the remaining days (`rem`) by using integer division (`//`) and modulo (`%`).\n - It then calculates the contribution from complete weeks using the formula for the sum of the first `n` natural numbers (`(n * (n - 1)) / 2`). In this case, `n` is the number of complete weeks (`week`).\n - The calculated sum is then multiplied by 7 to account for each day in a week.\n\n2. **Remaining Days Contribution:**\n - The code calculates the sum of an arithmetic series for the remaining days (`rem`) using the formula `((n * (n + 1)) / 2)`, where `n` is the number of remaining days. This part represents the contribution from regular days.\n - Additionally, it adds the contribution from the extra amount Hercy puts in on Mondays. This is achieved by adding `(week * rem)`, where `week` is the number of complete weeks and `rem` is the number of remaining days.\n\n3. **Combining Contributions:**\n - The total contribution from complete weeks and remaining days is then added together to get the final result.\n\nIn summary, the approach breaks down the problem into two components: the contribution from complete weeks and the contribution from remaining days. It uses arithmetic series formulas to calculate these contributions efficiently, and the final total is obtained by summing these contributions. The use of integer division and modulo ensures that the code considers both complete weeks and remaining days accurately. The time and space complexity are constant, making the solution efficient.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity is O(1) because the calculations involve simple arithmetic operations and do not depend on the size of the input `n`.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is also O(1) as there is a constant amount of extra space used regardless of the input size.\n\n# Code\n```\nclass Solution:\n def totalMoney(self, n: int) -> int:\n total = 0\n week = n//7\n rem = n%7\n\n total +=(28*week)\n total += ((rem*(rem+1))//2 + (week*rem))\n total += ((week*(week-1))//2)*7\n\n return total\n\n #Sc and Tc = O(1)\n```
1
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**. He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put 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:** * `1 <= n <= 1000`
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
Mathematical Approach | T.C. - O(1) | Beginner Friendly | Explanation - [Video] | Easy Solution
calculate-money-in-leetcode-bank
0
1
For better understanding of the question you can also check out this video. Hope it helps.\n\nhttps://youtu.be/3Pjay2_v-os\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n1. **Contribution from complete weeks:** The code calculates the total contribution from complete weeks using the formula for the sum of the first `n` natural numbers. The total contribution is then multiplied by 7 to account for each day in a week.\n\n2. **Contribution from remaining days:** The code calculates the sum of an arithmetic series for the remaining days, including the additional contributions on Mondays. This contribution is added to the total.\n\n3. **Final Total:** The total contributions from complete weeks and remaining days are added together to get the final total amount Hercy puts in the bank.\n\nPlease subscribe to my channel if it helped you.\nhttps://www.youtube.com/channel/UCsu5CDZmlHcpH7dQozZWtQw?sub_confirmation=1\n\nCurrent subscribers: 213\nTarget subscribers: 250\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Complete Weeks Contribution:**\n - The code first calculates the number of complete weeks (`week`) and the remaining days (`rem`) by using integer division (`//`) and modulo (`%`).\n - It then calculates the contribution from complete weeks using the formula for the sum of the first `n` natural numbers (`(n * (n - 1)) / 2`). In this case, `n` is the number of complete weeks (`week`).\n - The calculated sum is then multiplied by 7 to account for each day in a week.\n\n2. **Remaining Days Contribution:**\n - The code calculates the sum of an arithmetic series for the remaining days (`rem`) using the formula `((n * (n + 1)) / 2)`, where `n` is the number of remaining days. This part represents the contribution from regular days.\n - Additionally, it adds the contribution from the extra amount Hercy puts in on Mondays. This is achieved by adding `(week * rem)`, where `week` is the number of complete weeks and `rem` is the number of remaining days.\n\n3. **Combining Contributions:**\n - The total contribution from complete weeks and remaining days is then added together to get the final result.\n\nIn summary, the approach breaks down the problem into two components: the contribution from complete weeks and the contribution from remaining days. It uses arithmetic series formulas to calculate these contributions efficiently, and the final total is obtained by summing these contributions. The use of integer division and modulo ensures that the code considers both complete weeks and remaining days accurately. The time and space complexity are constant, making the solution efficient.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity is O(1) because the calculations involve simple arithmetic operations and do not depend on the size of the input `n`.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is also O(1) as there is a constant amount of extra space used regardless of the input size.\n\n# Code\n```\nclass Solution:\n def totalMoney(self, n: int) -> int:\n total = 0\n week = n//7\n rem = n%7\n\n total +=(28*week)\n total += ((rem*(rem+1))//2 + (week*rem))\n total += ((week*(week-1))//2)*7\n\n return total\n\n #Sc and Tc = O(1)\n```
1
You are given the logs for users' actions on LeetCode, and an integer `k`. The logs are represented by a 2D integer array `logs` where each `logs[i] = [IDi, timei]` indicates that the user with `IDi` performed an action at the minute `timei`. **Multiple users** can perform actions simultaneously, and a single user can perform **multiple actions** in the same minute. The **user active minutes (UAM)** for a given user is defined as the **number of unique minutes** in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it. You are to calculate a **1-indexed** array `answer` of size `k` such that, for each `j` (`1 <= j <= k`), `answer[j]` is the **number of users** whose **UAM** equals `j`. Return _the array_ `answer` _as described above_. **Example 1:** **Input:** logs = \[\[0,5\],\[1,2\],\[0,2\],\[0,5\],\[1,3\]\], k = 5 **Output:** \[0,2,0,0,0\] **Explanation:** The user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once). The user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. Since both users have a UAM of 2, answer\[2\] is 2, and the remaining answer\[j\] values are 0. **Example 2:** **Input:** logs = \[\[1,1\],\[2,2\],\[2,3\]\], k = 4 **Output:** \[1,1,0,0\] **Explanation:** The user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1. The user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. There is one user with a UAM of 1 and one with a UAM of 2. Hence, answer\[1\] = 1, answer\[2\] = 1, and the remaining values are 0. **Constraints:** * `1 <= logs.length <= 104` * `0 <= IDi <= 109` * `1 <= timei <= 105` * `k` is in the range `[The maximum **UAM** for a user, 105]`.
Simulate the process by keeping track of how much money John is putting in and which day of the week it is, and use this information to deduce how much money John will put in the next day.
✅Unlocking Wealth Accumulation Patterns: Navigating LeetCode's Total Money Earned Challenge
calculate-money-in-leetcode-bank
1
1
# Exploring Wealth Accumulation Patterns: LeetCode\'s Total Money Earned Challenge\n\n## \uD83D\uDCB0 Problem Overview\nLeetCode introduces us to a fascinating financial challenge with the "Total Money Earned" problem. In this blog post, we\'ll delve into the problem\'s intricacies and provide a comprehensive guide to solving it efficiently.\n\n## \uD83E\uDD14 Problem Statement\nGiven the number of weeks `n`, where each week consists of seven days, the task is to calculate the total money earned over `n` weeks. The earning pattern is unique - starting from $$ $1 $$ on the first day, the daily earnings increase by one dollar each subsequent day. At the beginning of each week (on Mondays), the earnings reset to $$ $1 $$.\n\n## \uD83D\uDCA1 Approach: Calculating Wealth Accumulation\nTo tackle this problem, we adopt a systematic approach. For each day, we determine the corresponding week and day within that week. Based on this, we calculate the earnings for that day, considering the reset on Mondays. By iteratively summing up the daily earnings, we obtain the total money earned over the specified number of weeks.\n\n### Algorithm Steps:\n1. Initialize variables for total cost (`totCost`) and the current week\'s earnings (`mon`).\n2. Iterate through each day, calculating earnings and updating the total cost accordingly.\n3. Handle the reset of earnings at the beginning of each week.\n\n## \uD83E\uDDD0 Code Breakdown\nLet\'s dissect the C++ code to understand each part:\n```cpp []\nint totalMoney(int n) {\n int totCost = 0, mon = 0;\n for (int i = 0; i < n; i++) {\n if (i % 7 == 0) {\n mon = i / 7 + 1;\n totCost += mon;\n } else {\n totCost += (mon + i % 7);\n }\n }\n return totCost;\n}\n```\n\n```python []\ndef totalMoney(n):\n tot_cost = 0\n mon = 0\n for i in range(n):\n if i % 7 == 0:\n mon = i // 7 + 1\n tot_cost += mon\n else:\n tot_cost += (mon + i % 7)\n return tot_cost\n```\n\n```java []\npublic class Solution {\n public int totalMoney(int n) {\n int totCost = 0, mon = 0;\n for (int i = 0; i < n; i++) {\n if (i % 7 == 0) {\n mon = i / 7 + 1;\n totCost += mon;\n } else {\n totCost += (mon + i % 7);\n }\n }\n return totCost;\n }\n}\n```\n\n```csharp []\npublic class Solution {\n public int TotalMoney(int n) {\n int totCost = 0, mon = 0;\n for (int i = 0; i < n; i++) {\n if (i % 7 == 0) {\n mon = i / 7 + 1;\n totCost += mon;\n } else {\n totCost += (mon + i % 7);\n }\n }\n return totCost;\n }\n}\n```\n\n```javascript []\nfunction totalMoney(n) {\n let totCost = 0, mon = 0;\n for (let i = 0; i < n; i++) {\n if (i % 7 === 0) {\n mon = Math.floor(i / 7) + 1;\n totCost += mon;\n } else {\n totCost += (mon + i % 7);\n }\n }\n return totCost;\n}\n```\n\n```ruby []\ndef total_money(n)\n tot_cost = 0\n mon = 0\n (0...n).each do |i|\n if i % 7 == 0\n mon = i / 7 + 1\n tot_cost += mon\n else\n tot_cost += (mon + i % 7)\n end\n end\n tot_cost\nend\n```\n\n\n## \uD83D\uDE80 Complexity Analysis\n- **Time Complexity:** O(n) - Linear time complexity as we iterate through each day.\n- **Space Complexity:** O(1) - Constant space for variables.\n\n## \uD83C\uDF93 Conclusion\nIn this blog post, we\'ve navigated through the intricacies of LeetCode\'s "Total Money Earned" challenge. By breaking down the problem, understanding the earning pattern, and implementing a systematic algorithm, we\'ve unlocked an efficient solution.\n\nFeel free to explore variations of this problem and practice on LeetCode to enhance your algorithmic skills. Happy coding!\n\n---\n# Approach 2: Mathematical Insight\nIn the second approach, we leverage a mathematical formula to directly compute the total money earned over a given number of weeks. The formula helps us skip the iterative process and simplifies the calculation.\n\n### Steps:\n- We calculate the number of complete weeks and the remaining days.\n- We use a formula to find the sum of earnings for complete weeks.\n- We use another formula to find the earnings for the remaining days.\n- We add the results of both formulas to get the total money earned.\n\n## Code\n``` cpp []\nclass Solution\n{\n public:\n int totalMoney(int n) {\n int fullWeeks = n / 7;\n int remainingDays = n % 7;\n\n // Calculate the sum of earnings for complete weeks using the sum of the first k natural numbers formula\n int totalWeeksEarnings = (49 + 7 * fullWeeks) * fullWeeks / 2;\n\n // Calculate earnings for the remaining days using a modified formula\n int additionalEarnings = (2 * fullWeeks + remainingDays + 1) * remainingDays / 2;\n\n // Return the total money earned\n return totalWeeksEarnings + additionalEarnings;\n}};\n```\n\n```python []\nclass Solution:\n def totalMoney(self, n: int) -> int:\n full_weeks = n // 7\n remaining_days = n % 7\n\n # Calculate the sum of earnings for complete weeks using the sum of the first k natural numbers formula\n total_weeks_earnings = (49 + 7 * full_weeks) * full_weeks // 2\n\n # Calculate earnings for the remaining days using a modified formula\n additional_earnings = (2 * full_weeks + remaining_days + 1) * remaining_days // 2\n\n # Return the total money earned\n return total_weeks_earnings + additional_earnings\n```\n\n```java []\npublic class Solution {\n public int totalMoney(int n) {\n int fullWeeks = n / 7;\n int remainingDays = n % 7;\n\n // Calculate the sum of earnings for complete weeks using the sum of the first k natural numbers formula\n int totalWeeksEarnings = (49 + 7 * fullWeeks) * fullWeeks / 2;\n\n // Calculate earnings for the remaining days using a modified formula\n int additionalEarnings = (2 * fullWeeks + remainingDays + 1) * remainingDays / 2;\n\n // Return the total money earned\n return totalWeeksEarnings + additionalEarnings;\n }\n}\n```\n\n```csharp []\npublic class Solution {\n public int TotalMoney(int n) {\n int fullWeeks = n / 7;\n int remainingDays = n % 7;\n\n // Calculate the sum of earnings for complete weeks using the sum of the first k natural numbers formula\n int totalWeeksEarnings = (49 + 7 * fullWeeks) * fullWeeks / 2;\n\n // Calculate earnings for the remaining days using a modified formula\n int additionalEarnings = (2 * fullWeeks + remainingDays + 1) * remainingDays / 2;\n\n // Return the total money earned\n return totalWeeksEarnings + additionalEarnings;\n }\n}\n```\n\n```javascript []\nclass Solution {\n totalMoney(n) {\n const fullWeeks = Math.floor(n / 7);\n const remainingDays = n % 7;\n\n // Calculate the sum of earnings for complete weeks using the sum of the first k natural numbers formula\n const totalWeeksEarnings = (49 + 7 * fullWeeks) * fullWeeks / 2;\n\n // Calculate earnings for the remaining days using a modified formula\n const additionalEarnings = (2 * fullWeeks + remainingDays + 1) * remainingDays / 2;\n\n // Return the total money earned\n return totalWeeksEarnings + additionalEarnings;\n }\n}\n```\n\n```ruby []\nclass Solution\n def total_money(n)\n full_weeks = n / 7\n remaining_days = n % 7\n\n # Calculate the sum of earnings for complete weeks using the sum of the first k natural numbers formula\n total_weeks_earnings = (49 + 7 * full_weeks) * full_weeks / 2\n\n # Calculate earnings for the remaining days using a modified formula\n additional_earnings = (2 * full_weeks + remaining_days + 1) * remaining_days / 2\n\n # Return the total money earned\n total_weeks_earnings + additional_earnings\n end\nend\n```\n---\n# Consider UPVOTING\u2B06\uFE0F\n\n\n# DROP YOUR SUGGESTIONS IN THE COMMENT\n\n## Keep Coding\uD83E\uDDD1\u200D\uD83D\uDCBB\n\n\n-- *LB Signing Off*
1
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**. He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put 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:** * `1 <= n <= 1000`
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
✅Unlocking Wealth Accumulation Patterns: Navigating LeetCode's Total Money Earned Challenge
calculate-money-in-leetcode-bank
1
1
# Exploring Wealth Accumulation Patterns: LeetCode\'s Total Money Earned Challenge\n\n## \uD83D\uDCB0 Problem Overview\nLeetCode introduces us to a fascinating financial challenge with the "Total Money Earned" problem. In this blog post, we\'ll delve into the problem\'s intricacies and provide a comprehensive guide to solving it efficiently.\n\n## \uD83E\uDD14 Problem Statement\nGiven the number of weeks `n`, where each week consists of seven days, the task is to calculate the total money earned over `n` weeks. The earning pattern is unique - starting from $$ $1 $$ on the first day, the daily earnings increase by one dollar each subsequent day. At the beginning of each week (on Mondays), the earnings reset to $$ $1 $$.\n\n## \uD83D\uDCA1 Approach: Calculating Wealth Accumulation\nTo tackle this problem, we adopt a systematic approach. For each day, we determine the corresponding week and day within that week. Based on this, we calculate the earnings for that day, considering the reset on Mondays. By iteratively summing up the daily earnings, we obtain the total money earned over the specified number of weeks.\n\n### Algorithm Steps:\n1. Initialize variables for total cost (`totCost`) and the current week\'s earnings (`mon`).\n2. Iterate through each day, calculating earnings and updating the total cost accordingly.\n3. Handle the reset of earnings at the beginning of each week.\n\n## \uD83E\uDDD0 Code Breakdown\nLet\'s dissect the C++ code to understand each part:\n```cpp []\nint totalMoney(int n) {\n int totCost = 0, mon = 0;\n for (int i = 0; i < n; i++) {\n if (i % 7 == 0) {\n mon = i / 7 + 1;\n totCost += mon;\n } else {\n totCost += (mon + i % 7);\n }\n }\n return totCost;\n}\n```\n\n```python []\ndef totalMoney(n):\n tot_cost = 0\n mon = 0\n for i in range(n):\n if i % 7 == 0:\n mon = i // 7 + 1\n tot_cost += mon\n else:\n tot_cost += (mon + i % 7)\n return tot_cost\n```\n\n```java []\npublic class Solution {\n public int totalMoney(int n) {\n int totCost = 0, mon = 0;\n for (int i = 0; i < n; i++) {\n if (i % 7 == 0) {\n mon = i / 7 + 1;\n totCost += mon;\n } else {\n totCost += (mon + i % 7);\n }\n }\n return totCost;\n }\n}\n```\n\n```csharp []\npublic class Solution {\n public int TotalMoney(int n) {\n int totCost = 0, mon = 0;\n for (int i = 0; i < n; i++) {\n if (i % 7 == 0) {\n mon = i / 7 + 1;\n totCost += mon;\n } else {\n totCost += (mon + i % 7);\n }\n }\n return totCost;\n }\n}\n```\n\n```javascript []\nfunction totalMoney(n) {\n let totCost = 0, mon = 0;\n for (let i = 0; i < n; i++) {\n if (i % 7 === 0) {\n mon = Math.floor(i / 7) + 1;\n totCost += mon;\n } else {\n totCost += (mon + i % 7);\n }\n }\n return totCost;\n}\n```\n\n```ruby []\ndef total_money(n)\n tot_cost = 0\n mon = 0\n (0...n).each do |i|\n if i % 7 == 0\n mon = i / 7 + 1\n tot_cost += mon\n else\n tot_cost += (mon + i % 7)\n end\n end\n tot_cost\nend\n```\n\n\n## \uD83D\uDE80 Complexity Analysis\n- **Time Complexity:** O(n) - Linear time complexity as we iterate through each day.\n- **Space Complexity:** O(1) - Constant space for variables.\n\n## \uD83C\uDF93 Conclusion\nIn this blog post, we\'ve navigated through the intricacies of LeetCode\'s "Total Money Earned" challenge. By breaking down the problem, understanding the earning pattern, and implementing a systematic algorithm, we\'ve unlocked an efficient solution.\n\nFeel free to explore variations of this problem and practice on LeetCode to enhance your algorithmic skills. Happy coding!\n\n---\n# Approach 2: Mathematical Insight\nIn the second approach, we leverage a mathematical formula to directly compute the total money earned over a given number of weeks. The formula helps us skip the iterative process and simplifies the calculation.\n\n### Steps:\n- We calculate the number of complete weeks and the remaining days.\n- We use a formula to find the sum of earnings for complete weeks.\n- We use another formula to find the earnings for the remaining days.\n- We add the results of both formulas to get the total money earned.\n\n## Code\n``` cpp []\nclass Solution\n{\n public:\n int totalMoney(int n) {\n int fullWeeks = n / 7;\n int remainingDays = n % 7;\n\n // Calculate the sum of earnings for complete weeks using the sum of the first k natural numbers formula\n int totalWeeksEarnings = (49 + 7 * fullWeeks) * fullWeeks / 2;\n\n // Calculate earnings for the remaining days using a modified formula\n int additionalEarnings = (2 * fullWeeks + remainingDays + 1) * remainingDays / 2;\n\n // Return the total money earned\n return totalWeeksEarnings + additionalEarnings;\n}};\n```\n\n```python []\nclass Solution:\n def totalMoney(self, n: int) -> int:\n full_weeks = n // 7\n remaining_days = n % 7\n\n # Calculate the sum of earnings for complete weeks using the sum of the first k natural numbers formula\n total_weeks_earnings = (49 + 7 * full_weeks) * full_weeks // 2\n\n # Calculate earnings for the remaining days using a modified formula\n additional_earnings = (2 * full_weeks + remaining_days + 1) * remaining_days // 2\n\n # Return the total money earned\n return total_weeks_earnings + additional_earnings\n```\n\n```java []\npublic class Solution {\n public int totalMoney(int n) {\n int fullWeeks = n / 7;\n int remainingDays = n % 7;\n\n // Calculate the sum of earnings for complete weeks using the sum of the first k natural numbers formula\n int totalWeeksEarnings = (49 + 7 * fullWeeks) * fullWeeks / 2;\n\n // Calculate earnings for the remaining days using a modified formula\n int additionalEarnings = (2 * fullWeeks + remainingDays + 1) * remainingDays / 2;\n\n // Return the total money earned\n return totalWeeksEarnings + additionalEarnings;\n }\n}\n```\n\n```csharp []\npublic class Solution {\n public int TotalMoney(int n) {\n int fullWeeks = n / 7;\n int remainingDays = n % 7;\n\n // Calculate the sum of earnings for complete weeks using the sum of the first k natural numbers formula\n int totalWeeksEarnings = (49 + 7 * fullWeeks) * fullWeeks / 2;\n\n // Calculate earnings for the remaining days using a modified formula\n int additionalEarnings = (2 * fullWeeks + remainingDays + 1) * remainingDays / 2;\n\n // Return the total money earned\n return totalWeeksEarnings + additionalEarnings;\n }\n}\n```\n\n```javascript []\nclass Solution {\n totalMoney(n) {\n const fullWeeks = Math.floor(n / 7);\n const remainingDays = n % 7;\n\n // Calculate the sum of earnings for complete weeks using the sum of the first k natural numbers formula\n const totalWeeksEarnings = (49 + 7 * fullWeeks) * fullWeeks / 2;\n\n // Calculate earnings for the remaining days using a modified formula\n const additionalEarnings = (2 * fullWeeks + remainingDays + 1) * remainingDays / 2;\n\n // Return the total money earned\n return totalWeeksEarnings + additionalEarnings;\n }\n}\n```\n\n```ruby []\nclass Solution\n def total_money(n)\n full_weeks = n / 7\n remaining_days = n % 7\n\n # Calculate the sum of earnings for complete weeks using the sum of the first k natural numbers formula\n total_weeks_earnings = (49 + 7 * full_weeks) * full_weeks / 2\n\n # Calculate earnings for the remaining days using a modified formula\n additional_earnings = (2 * full_weeks + remaining_days + 1) * remaining_days / 2\n\n # Return the total money earned\n total_weeks_earnings + additional_earnings\n end\nend\n```\n---\n# Consider UPVOTING\u2B06\uFE0F\n\n\n# DROP YOUR SUGGESTIONS IN THE COMMENT\n\n## Keep Coding\uD83E\uDDD1\u200D\uD83D\uDCBB\n\n\n-- *LB Signing Off*
1
You are given the logs for users' actions on LeetCode, and an integer `k`. The logs are represented by a 2D integer array `logs` where each `logs[i] = [IDi, timei]` indicates that the user with `IDi` performed an action at the minute `timei`. **Multiple users** can perform actions simultaneously, and a single user can perform **multiple actions** in the same minute. The **user active minutes (UAM)** for a given user is defined as the **number of unique minutes** in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it. You are to calculate a **1-indexed** array `answer` of size `k` such that, for each `j` (`1 <= j <= k`), `answer[j]` is the **number of users** whose **UAM** equals `j`. Return _the array_ `answer` _as described above_. **Example 1:** **Input:** logs = \[\[0,5\],\[1,2\],\[0,2\],\[0,5\],\[1,3\]\], k = 5 **Output:** \[0,2,0,0,0\] **Explanation:** The user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once). The user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. Since both users have a UAM of 2, answer\[2\] is 2, and the remaining answer\[j\] values are 0. **Example 2:** **Input:** logs = \[\[1,1\],\[2,2\],\[2,3\]\], k = 4 **Output:** \[1,1,0,0\] **Explanation:** The user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1. The user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. There is one user with a UAM of 1 and one with a UAM of 2. Hence, answer\[1\] = 1, answer\[2\] = 1, and the remaining values are 0. **Constraints:** * `1 <= logs.length <= 104` * `0 <= IDi <= 109` * `1 <= timei <= 105` * `k` is in the range `[The maximum **UAM** for a user, 105]`.
Simulate the process by keeping track of how much money John is putting in and which day of the week it is, and use this information to deduce how much money John will put in the next day.
Python solution with explanation💃🏻
maximum-score-from-removing-substrings
0
1
```\nclass Solution:\n def maximumGain(self, s: str, x: int, y: int) -> int:\n\t\t# to calculate first, high value of x or y\n a, b = \'ab\', \'ba\'\n if y > x:\n b, a, y, x = a, b, x, y\n\n answer = 0\n \n for word in [a, b]:\n stack = []\n\n i = 0\n while i < len(s):\n stack.append(s[i])\n \n n = len(stack)\n prefix = stack[n-2] + stack[n-1]\n # if see the prefix ab or ba move from stack and increment the answer\n if prefix == word:\n answer += x\n stack.pop()\n stack.pop()\n i += 1\n # change the x point to y for 2nd iteration\n x = y\n \n # assign new letters with already removed prefix\n s = \'\'.join(stack)\n return answer\n```
9
You are given a string `s` and two integers `x` and `y`. You can perform two types of operations any number of times. * Remove substring `"ab "` and gain `x` points. * For example, when removing `"ab "` from `"cabxbae "` it becomes `"cxbae "`. * Remove substring `"ba "` and gain `y` points. * For example, when removing `"ba "` from `"cabxbae "` it becomes `"cabxe "`. Return _the maximum points you can gain after applying the above operations on_ `s`. **Example 1:** **Input:** s = "cdbcbbaaabab ", x = 4, y = 5 **Output:** 19 **Explanation:** - Remove the "ba " underlined in "cdbcbbaaabab ". Now, s = "cdbcbbaaab " and 5 points are added to the score. - Remove the "ab " underlined in "cdbcbbaaab ". Now, s = "cdbcbbaa " and 4 points are added to the score. - Remove the "ba " underlined in "cdbcbbaa ". Now, s = "cdbcba " and 5 points are added to the score. - Remove the "ba " underlined in "cdbcba ". Now, s = "cdbc " and 5 points are added to the score. Total score = 5 + 4 + 5 + 5 = 19. **Example 2:** **Input:** s = "aabbaaxybbaabb ", x = 5, y = 4 **Output:** 20 **Constraints:** * `1 <= s.length <= 105` * `1 <= x, y <= 104` * `s` consists of lowercase English letters.
Each point on the left would either be connected to exactly point already connected to some left node, or a subset of the nodes on the right which are not connected to any node Use dynamic programming with bitmasking, where the state will be (number of points assigned in first group, bitmask of points assigned in second group).
Python solution with explanation💃🏻
maximum-score-from-removing-substrings
0
1
```\nclass Solution:\n def maximumGain(self, s: str, x: int, y: int) -> int:\n\t\t# to calculate first, high value of x or y\n a, b = \'ab\', \'ba\'\n if y > x:\n b, a, y, x = a, b, x, y\n\n answer = 0\n \n for word in [a, b]:\n stack = []\n\n i = 0\n while i < len(s):\n stack.append(s[i])\n \n n = len(stack)\n prefix = stack[n-2] + stack[n-1]\n # if see the prefix ab or ba move from stack and increment the answer\n if prefix == word:\n answer += x\n stack.pop()\n stack.pop()\n i += 1\n # change the x point to y for 2nd iteration\n x = y\n \n # assign new letters with already removed prefix\n s = \'\'.join(stack)\n return answer\n```
9
You are given two positive integer arrays `nums1` and `nums2`, both of length `n`. The **absolute sum difference** of arrays `nums1` and `nums2` is defined as the **sum** of `|nums1[i] - nums2[i]|` for each `0 <= i < n` (**0-indexed**). You can replace **at most one** element of `nums1` with **any** other element in `nums1` to **minimize** the absolute sum difference. Return the _minimum absolute sum difference **after** replacing at most one element in the array `nums1`._ Since the answer may be large, return it **modulo** `109 + 7`. `|x|` is defined as: * `x` if `x >= 0`, or * `-x` if `x < 0`. **Example 1:** **Input:** nums1 = \[1,7,5\], nums2 = \[2,3,5\] **Output:** 3 **Explanation:** There are two possible optimal solutions: - Replace the second element with the first: \[1,**7**,5\] => \[1,**1**,5\], or - Replace the second element with the third: \[1,**7**,5\] => \[1,**5**,5\]. Both will yield an absolute sum difference of `|1-2| + (|1-3| or |5-3|) + |5-5| =` 3. **Example 2:** **Input:** nums1 = \[2,4,6,8,10\], nums2 = \[2,4,6,8,10\] **Output:** 0 **Explanation:** nums1 is equal to nums2 so no replacement is needed. This will result in an absolute sum difference of 0. **Example 3:** **Input:** nums1 = \[1,10,4,4,2,7\], nums2 = \[9,3,5,1,7,4\] **Output:** 20 **Explanation:** Replace the first element with the second: \[**1**,10,4,4,2,7\] => \[**10**,10,4,4,2,7\]. This yields an absolute sum difference of `|10-9| + |10-3| + |4-5| + |4-1| + |2-7| + |7-4| = 20` **Constraints:** * `n == nums1.length` * `n == nums2.length` * `1 <= n <= 105` * `1 <= nums1[i], nums2[i] <= 105`
Note that it is always more optimal to take one type of substring before another You can use a stack to handle erasures
Solution using stack and map - Python!
maximum-score-from-removing-substrings
0
1
# Code\n```\nclass Solution:\n def maximumGain(self, s: str, x: int, y: int) -> int:\n m = {\'ab\':x, \'ba\':y}\n ab = m.keys()\n stack = sorted(ab, key=lambda x:m[x], reverse=True)\n score = 0\n \n bin = []\n \n for st in stack:\n for char in s:\n if bin and bin[-1]+char == st:\n score += m[st]\n bin.pop()\n else:\n bin.append(char)\n s = \'\'.join(bin)\n bin = []\n \n return score\n```
0
You are given a string `s` and two integers `x` and `y`. You can perform two types of operations any number of times. * Remove substring `"ab "` and gain `x` points. * For example, when removing `"ab "` from `"cabxbae "` it becomes `"cxbae "`. * Remove substring `"ba "` and gain `y` points. * For example, when removing `"ba "` from `"cabxbae "` it becomes `"cabxe "`. Return _the maximum points you can gain after applying the above operations on_ `s`. **Example 1:** **Input:** s = "cdbcbbaaabab ", x = 4, y = 5 **Output:** 19 **Explanation:** - Remove the "ba " underlined in "cdbcbbaaabab ". Now, s = "cdbcbbaaab " and 5 points are added to the score. - Remove the "ab " underlined in "cdbcbbaaab ". Now, s = "cdbcbbaa " and 4 points are added to the score. - Remove the "ba " underlined in "cdbcbbaa ". Now, s = "cdbcba " and 5 points are added to the score. - Remove the "ba " underlined in "cdbcba ". Now, s = "cdbc " and 5 points are added to the score. Total score = 5 + 4 + 5 + 5 = 19. **Example 2:** **Input:** s = "aabbaaxybbaabb ", x = 5, y = 4 **Output:** 20 **Constraints:** * `1 <= s.length <= 105` * `1 <= x, y <= 104` * `s` consists of lowercase English letters.
Each point on the left would either be connected to exactly point already connected to some left node, or a subset of the nodes on the right which are not connected to any node Use dynamic programming with bitmasking, where the state will be (number of points assigned in first group, bitmask of points assigned in second group).
Solution using stack and map - Python!
maximum-score-from-removing-substrings
0
1
# Code\n```\nclass Solution:\n def maximumGain(self, s: str, x: int, y: int) -> int:\n m = {\'ab\':x, \'ba\':y}\n ab = m.keys()\n stack = sorted(ab, key=lambda x:m[x], reverse=True)\n score = 0\n \n bin = []\n \n for st in stack:\n for char in s:\n if bin and bin[-1]+char == st:\n score += m[st]\n bin.pop()\n else:\n bin.append(char)\n s = \'\'.join(bin)\n bin = []\n \n return score\n```
0
You are given two positive integer arrays `nums1` and `nums2`, both of length `n`. The **absolute sum difference** of arrays `nums1` and `nums2` is defined as the **sum** of `|nums1[i] - nums2[i]|` for each `0 <= i < n` (**0-indexed**). You can replace **at most one** element of `nums1` with **any** other element in `nums1` to **minimize** the absolute sum difference. Return the _minimum absolute sum difference **after** replacing at most one element in the array `nums1`._ Since the answer may be large, return it **modulo** `109 + 7`. `|x|` is defined as: * `x` if `x >= 0`, or * `-x` if `x < 0`. **Example 1:** **Input:** nums1 = \[1,7,5\], nums2 = \[2,3,5\] **Output:** 3 **Explanation:** There are two possible optimal solutions: - Replace the second element with the first: \[1,**7**,5\] => \[1,**1**,5\], or - Replace the second element with the third: \[1,**7**,5\] => \[1,**5**,5\]. Both will yield an absolute sum difference of `|1-2| + (|1-3| or |5-3|) + |5-5| =` 3. **Example 2:** **Input:** nums1 = \[2,4,6,8,10\], nums2 = \[2,4,6,8,10\] **Output:** 0 **Explanation:** nums1 is equal to nums2 so no replacement is needed. This will result in an absolute sum difference of 0. **Example 3:** **Input:** nums1 = \[1,10,4,4,2,7\], nums2 = \[9,3,5,1,7,4\] **Output:** 20 **Explanation:** Replace the first element with the second: \[**1**,10,4,4,2,7\] => \[**10**,10,4,4,2,7\]. This yields an absolute sum difference of `|10-9| + |10-3| + |4-5| + |4-1| + |2-7| + |7-4| = 20` **Constraints:** * `n == nums1.length` * `n == nums2.length` * `1 <= n <= 105` * `1 <= nums1[i], nums2[i] <= 105`
Note that it is always more optimal to take one type of substring before another You can use a stack to handle erasures
Python O(n) solution (greedy approach)
maximum-score-from-removing-substrings
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nif x>y try to remove all \'ab\' first then all \'ba\'. Else vice-verca. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```\nclass Solution:\n def getPoints(self,s,status):\n a=\'a\'\n b=\'b\'\n p=self.x\n if status:\n a,b=b,a\n p=self.y\n stack=[]\n for i in s:\n if i==b and len(stack) and stack[-1]==a:\n stack.pop()\n self.points+=p\n else:\n stack.append(i)\n return stack\n\n\n\n \n def maximumGain(self, s: str, x: int, y: int) -> int:\n self.x=x\n self.y=y\n self.points=0\n if x>y:\n self.getPoints(self.getPoints(s,0),1)\n else:\n self.getPoints(self.getPoints(s,1),0)\n return self.points\n \n \n```
0
You are given a string `s` and two integers `x` and `y`. You can perform two types of operations any number of times. * Remove substring `"ab "` and gain `x` points. * For example, when removing `"ab "` from `"cabxbae "` it becomes `"cxbae "`. * Remove substring `"ba "` and gain `y` points. * For example, when removing `"ba "` from `"cabxbae "` it becomes `"cabxe "`. Return _the maximum points you can gain after applying the above operations on_ `s`. **Example 1:** **Input:** s = "cdbcbbaaabab ", x = 4, y = 5 **Output:** 19 **Explanation:** - Remove the "ba " underlined in "cdbcbbaaabab ". Now, s = "cdbcbbaaab " and 5 points are added to the score. - Remove the "ab " underlined in "cdbcbbaaab ". Now, s = "cdbcbbaa " and 4 points are added to the score. - Remove the "ba " underlined in "cdbcbbaa ". Now, s = "cdbcba " and 5 points are added to the score. - Remove the "ba " underlined in "cdbcba ". Now, s = "cdbc " and 5 points are added to the score. Total score = 5 + 4 + 5 + 5 = 19. **Example 2:** **Input:** s = "aabbaaxybbaabb ", x = 5, y = 4 **Output:** 20 **Constraints:** * `1 <= s.length <= 105` * `1 <= x, y <= 104` * `s` consists of lowercase English letters.
Each point on the left would either be connected to exactly point already connected to some left node, or a subset of the nodes on the right which are not connected to any node Use dynamic programming with bitmasking, where the state will be (number of points assigned in first group, bitmask of points assigned in second group).
Python O(n) solution (greedy approach)
maximum-score-from-removing-substrings
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nif x>y try to remove all \'ab\' first then all \'ba\'. Else vice-verca. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```\nclass Solution:\n def getPoints(self,s,status):\n a=\'a\'\n b=\'b\'\n p=self.x\n if status:\n a,b=b,a\n p=self.y\n stack=[]\n for i in s:\n if i==b and len(stack) and stack[-1]==a:\n stack.pop()\n self.points+=p\n else:\n stack.append(i)\n return stack\n\n\n\n \n def maximumGain(self, s: str, x: int, y: int) -> int:\n self.x=x\n self.y=y\n self.points=0\n if x>y:\n self.getPoints(self.getPoints(s,0),1)\n else:\n self.getPoints(self.getPoints(s,1),0)\n return self.points\n \n \n```
0
You are given two positive integer arrays `nums1` and `nums2`, both of length `n`. The **absolute sum difference** of arrays `nums1` and `nums2` is defined as the **sum** of `|nums1[i] - nums2[i]|` for each `0 <= i < n` (**0-indexed**). You can replace **at most one** element of `nums1` with **any** other element in `nums1` to **minimize** the absolute sum difference. Return the _minimum absolute sum difference **after** replacing at most one element in the array `nums1`._ Since the answer may be large, return it **modulo** `109 + 7`. `|x|` is defined as: * `x` if `x >= 0`, or * `-x` if `x < 0`. **Example 1:** **Input:** nums1 = \[1,7,5\], nums2 = \[2,3,5\] **Output:** 3 **Explanation:** There are two possible optimal solutions: - Replace the second element with the first: \[1,**7**,5\] => \[1,**1**,5\], or - Replace the second element with the third: \[1,**7**,5\] => \[1,**5**,5\]. Both will yield an absolute sum difference of `|1-2| + (|1-3| or |5-3|) + |5-5| =` 3. **Example 2:** **Input:** nums1 = \[2,4,6,8,10\], nums2 = \[2,4,6,8,10\] **Output:** 0 **Explanation:** nums1 is equal to nums2 so no replacement is needed. This will result in an absolute sum difference of 0. **Example 3:** **Input:** nums1 = \[1,10,4,4,2,7\], nums2 = \[9,3,5,1,7,4\] **Output:** 20 **Explanation:** Replace the first element with the second: \[**1**,10,4,4,2,7\] => \[**10**,10,4,4,2,7\]. This yields an absolute sum difference of `|10-9| + |10-3| + |4-5| + |4-1| + |2-7| + |7-4| = 20` **Constraints:** * `n == nums1.length` * `n == nums2.length` * `1 <= n <= 105` * `1 <= nums1[i], nums2[i] <= 105`
Note that it is always more optimal to take one type of substring before another You can use a stack to handle erasures
Python 3 || 15 lines, backtrack || T/M: 77% / 78%
construct-the-lexicographically-largest-valid-sequence
0
1
```\nclass Solution:\n def constructDistancedSequence(self, n: int) -> List[int]:\n\n def backtrack(idx1 = 0): \n\n if not unseen: return True\n\n if ans[idx1]: return backtrack(idx1+1)\n\n for num in reversed(range(1,n+1)):\n\n idx2 = idx1 + num if num != 1 else idx1\n\n if num in unseen and idx2 < n+n-1 and not ans[idx2]:\n ans[idx1] = ans[idx2] = num\n unseen.remove(num)\n\n if backtrack(idx1+1): return True\n ans[idx1] = ans[idx2] = 0\n unseen.add(num)\n\n return False\n\n ans, unseen = [0]*(n+n-1), set(range(1,n+1))\n\n backtrack()\n\n return ans\n```\n[https://leetcode.com/problems/construct-the-lexicographically-largest-valid-sequence/submissions/937592483/](http://)\n\nI could be wrong, but I think that time complexity is *O*(*N!*) (worst-case) and space complexity is *O*(*N*).
3
Given an integer `n`, find a sequence that satisfies all of the following: * The integer `1` occurs once in the sequence. * Each integer between `2` and `n` occurs twice in the sequence. * For every integer `i` between `2` and `n`, the **distance** between the two occurrences of `i` is exactly `i`. The **distance** between two numbers on the sequence, `a[i]` and `a[j]`, is the absolute difference of their indices, `|j - i|`. Return _the **lexicographically largest** sequence__. It is guaranteed that under the given constraints, there is always a solution._ A sequence `a` is lexicographically larger than a sequence `b` (of the same length) if in the first position where `a` and `b` differ, sequence `a` has a number greater than the corresponding number in `b`. For example, `[0,1,9,0]` is lexicographically larger than `[0,1,5,6]` because the first position they differ is at the third number, and `9` is greater than `5`. **Example 1:** **Input:** n = 3 **Output:** \[3,1,2,3,2\] **Explanation:** \[2,3,2,1,3\] is also a valid sequence, but \[3,1,2,3,2\] is the lexicographically largest valid sequence. **Example 2:** **Input:** n = 5 **Output:** \[5,3,1,4,3,5,2,4,2\] **Constraints:** * `1 <= n <= 20`
null
Python 3 || 15 lines, backtrack || T/M: 77% / 78%
construct-the-lexicographically-largest-valid-sequence
0
1
```\nclass Solution:\n def constructDistancedSequence(self, n: int) -> List[int]:\n\n def backtrack(idx1 = 0): \n\n if not unseen: return True\n\n if ans[idx1]: return backtrack(idx1+1)\n\n for num in reversed(range(1,n+1)):\n\n idx2 = idx1 + num if num != 1 else idx1\n\n if num in unseen and idx2 < n+n-1 and not ans[idx2]:\n ans[idx1] = ans[idx2] = num\n unseen.remove(num)\n\n if backtrack(idx1+1): return True\n ans[idx1] = ans[idx2] = 0\n unseen.add(num)\n\n return False\n\n ans, unseen = [0]*(n+n-1), set(range(1,n+1))\n\n backtrack()\n\n return ans\n```\n[https://leetcode.com/problems/construct-the-lexicographically-largest-valid-sequence/submissions/937592483/](http://)\n\nI could be wrong, but I think that time complexity is *O*(*N!*) (worst-case) and space complexity is *O*(*N*).
3
You are given an array `nums` that consists of positive integers. The **GCD** of a sequence of numbers is defined as the greatest integer that divides **all** the numbers in the sequence evenly. * For example, the GCD of the sequence `[4,6,16]` is `2`. A **subsequence** of an array is a sequence that can be formed by removing some elements (possibly none) of the array. * For example, `[2,5,10]` is a subsequence of `[1,2,1,**2**,4,1,**5**,**10**]`. Return _the **number** of **different** GCDs among all **non-empty** subsequences of_ `nums`. **Example 1:** **Input:** nums = \[6,10,3\] **Output:** 5 **Explanation:** The figure shows all the non-empty subsequences and their GCDs. The different GCDs are 6, 10, 3, 2, and 1. **Example 2:** **Input:** nums = \[5,15,40,5,6\] **Output:** 7 **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 2 * 105`
Heuristic algorithm may work.
Python Greedy+Backtracking | Well Explained | Comments
construct-the-lexicographically-largest-valid-sequence
0
1
The array contains `2*n-1` elements since `1` occurs once and others twice.\n\nThe basic idea is, we try to put numbers into the array in a greedy way, since it requires **the only "Lexicographically Largest"** one.\nWe try numbers from `n` to `1` from beginning of the array.\nEach time we put `x` into the array at index `i`. If `x > 2`, we put another `x` at index `i+x`.\nNote that we must ensure the availability of indecies `i` and `i+x` for any `x`, `x>2`\nWe stop when the array is successfully filled.\n```\nclass Solution:\n def constructDistancedSequence(self, n: int) -> List[int]:\n \n arr = [0]*(2*n-1) # the array we want to put numbers. 0 means no number has been put here\n i = 0 # current index to put a number \n vi = [False] * (n+1) # check if we have used that number\n \n\t\t# backtracking\n def dfs(arr, i, vi):\n\t\t # if we already fill the array successfully, return True\n if i >= (2*n-1):\n return True\n\t\t\t\t\n\t\t\t# try each number from n to 1\n for x in range(n, 0, -1):\n\t\t\t # two cases:\n\t\t\t # x > 1, we check two places. Mind index out of bound here.\n\t\t\t # x = 1, we only check one place\n\t\t\t\t# arr[i] == 0 means index i is not occupied\n if (x > 1 and ((not (arr[i] == 0 and (i+x < 2*n-1) and arr[i+x] == 0)) or vi[x])) \\\n\t\t\t\t\tor (x == 1 and (arr[i] != 0 or vi[x])):\n continue\n\t\t\t\t\n\t\t\t\t# if it can be placed, then place it\n if x > 1:\n arr[i] = x\n arr[i+x] = x\n else:\n arr[i] = x\n vi[x] = True\n\t\t\t\t\n\t\t\t\t# find the next available place\n nexti = i+1\n while nexti < 2*n-1 and arr[nexti]:\n nexti += 1\n\t\t\t\t\n\t\t\t\t# place the next one\n if dfs(arr, nexti, vi):\n\t\t\t\t\t# if it success, it is already the lexicographically largest one, we don\'t search anymore\n return True\n\t\t\t\t\t\n\t\t\t\t# backtracking... restore the state\n if x > 1:\n arr[i] = 0\n arr[i+x] = 0\n else:\n arr[i] = 0\n vi[x] = False\n\t\t\t\n\t\t\t# we could not find a solution, return False\n return False\n\t\t\n dfs(arr, i, vi)\n return arr\n \n```
25
Given an integer `n`, find a sequence that satisfies all of the following: * The integer `1` occurs once in the sequence. * Each integer between `2` and `n` occurs twice in the sequence. * For every integer `i` between `2` and `n`, the **distance** between the two occurrences of `i` is exactly `i`. The **distance** between two numbers on the sequence, `a[i]` and `a[j]`, is the absolute difference of their indices, `|j - i|`. Return _the **lexicographically largest** sequence__. It is guaranteed that under the given constraints, there is always a solution._ A sequence `a` is lexicographically larger than a sequence `b` (of the same length) if in the first position where `a` and `b` differ, sequence `a` has a number greater than the corresponding number in `b`. For example, `[0,1,9,0]` is lexicographically larger than `[0,1,5,6]` because the first position they differ is at the third number, and `9` is greater than `5`. **Example 1:** **Input:** n = 3 **Output:** \[3,1,2,3,2\] **Explanation:** \[2,3,2,1,3\] is also a valid sequence, but \[3,1,2,3,2\] is the lexicographically largest valid sequence. **Example 2:** **Input:** n = 5 **Output:** \[5,3,1,4,3,5,2,4,2\] **Constraints:** * `1 <= n <= 20`
null
Python Greedy+Backtracking | Well Explained | Comments
construct-the-lexicographically-largest-valid-sequence
0
1
The array contains `2*n-1` elements since `1` occurs once and others twice.\n\nThe basic idea is, we try to put numbers into the array in a greedy way, since it requires **the only "Lexicographically Largest"** one.\nWe try numbers from `n` to `1` from beginning of the array.\nEach time we put `x` into the array at index `i`. If `x > 2`, we put another `x` at index `i+x`.\nNote that we must ensure the availability of indecies `i` and `i+x` for any `x`, `x>2`\nWe stop when the array is successfully filled.\n```\nclass Solution:\n def constructDistancedSequence(self, n: int) -> List[int]:\n \n arr = [0]*(2*n-1) # the array we want to put numbers. 0 means no number has been put here\n i = 0 # current index to put a number \n vi = [False] * (n+1) # check if we have used that number\n \n\t\t# backtracking\n def dfs(arr, i, vi):\n\t\t # if we already fill the array successfully, return True\n if i >= (2*n-1):\n return True\n\t\t\t\t\n\t\t\t# try each number from n to 1\n for x in range(n, 0, -1):\n\t\t\t # two cases:\n\t\t\t # x > 1, we check two places. Mind index out of bound here.\n\t\t\t # x = 1, we only check one place\n\t\t\t\t# arr[i] == 0 means index i is not occupied\n if (x > 1 and ((not (arr[i] == 0 and (i+x < 2*n-1) and arr[i+x] == 0)) or vi[x])) \\\n\t\t\t\t\tor (x == 1 and (arr[i] != 0 or vi[x])):\n continue\n\t\t\t\t\n\t\t\t\t# if it can be placed, then place it\n if x > 1:\n arr[i] = x\n arr[i+x] = x\n else:\n arr[i] = x\n vi[x] = True\n\t\t\t\t\n\t\t\t\t# find the next available place\n nexti = i+1\n while nexti < 2*n-1 and arr[nexti]:\n nexti += 1\n\t\t\t\t\n\t\t\t\t# place the next one\n if dfs(arr, nexti, vi):\n\t\t\t\t\t# if it success, it is already the lexicographically largest one, we don\'t search anymore\n return True\n\t\t\t\t\t\n\t\t\t\t# backtracking... restore the state\n if x > 1:\n arr[i] = 0\n arr[i+x] = 0\n else:\n arr[i] = 0\n vi[x] = False\n\t\t\t\n\t\t\t# we could not find a solution, return False\n return False\n\t\t\n dfs(arr, i, vi)\n return arr\n \n```
25
You are given an array `nums` that consists of positive integers. The **GCD** of a sequence of numbers is defined as the greatest integer that divides **all** the numbers in the sequence evenly. * For example, the GCD of the sequence `[4,6,16]` is `2`. A **subsequence** of an array is a sequence that can be formed by removing some elements (possibly none) of the array. * For example, `[2,5,10]` is a subsequence of `[1,2,1,**2**,4,1,**5**,**10**]`. Return _the **number** of **different** GCDs among all **non-empty** subsequences of_ `nums`. **Example 1:** **Input:** nums = \[6,10,3\] **Output:** 5 **Explanation:** The figure shows all the non-empty subsequences and their GCDs. The different GCDs are 6, 10, 3, 2, and 1. **Example 2:** **Input:** nums = \[5,15,40,5,6\] **Output:** 7 **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 2 * 105`
Heuristic algorithm may work.
Python3 solution: ternary operators
construct-the-lexicographically-largest-valid-sequence
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nPut the integers in from left to right, and from large to small. Whenver we can fill the array, we have the answer\n# Approach\n<!-- Describe your approach to solving the problem. -->\nStandard backtracking. The answer is found whenever we reach the end\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nI tried larger $n$, and found that when $n$ is $39$, the calculation suddenly takes very long, probably because this is the first number in which the question setup breaks down.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n# Code\n```\n#\n# @lc app=leetcode id=1718 lang=python3\n#\n# [1718] Construct the Lexicographically Largest Valid Sequence\n#\n\n# @lc code=start\nfrom typing import List\n\n\nclass Solution:\n \'\'\'\n Put the integers in from left to right, and from large to small. Whenver we can fill the array, we have the answer\n \'\'\' \n\n def backtrack(self, i):\n if i == 2*self.n - 1:\n self.ans = [num for num in self.arr]\n return True\n elif self.arr[i] > 0:\n return self.backtrack(i + 1)\n else:\n for j in range(self.n, 0, -1):\n if j not in self.used and (i + j < 2*self.n - 1 if j > 1 else True) and self.arr[i] == 0 and (True if j == 1 else self.arr[i + j] == 0):\n self.used.add(j)\n self.arr[i] = j\n if j > 1:\n self.arr[i + j] = j\n if self.backtrack(i + 1):\n return True\n self.arr[i] = 0\n if j > 1:\n self.arr[i + j] = 0\n self.used.remove(j)\n return False\n\n\n def constructDistancedSequence(self, n: int) -> List[int]:\n self.arr = [0 for i in range(2*n - 1)]\n self.used = set()\n self.n = n\n self.ans = []\n found = self.backtrack(0)\n return self.ans\n \n\n \n# @lc code=end\n\n```
0
Given an integer `n`, find a sequence that satisfies all of the following: * The integer `1` occurs once in the sequence. * Each integer between `2` and `n` occurs twice in the sequence. * For every integer `i` between `2` and `n`, the **distance** between the two occurrences of `i` is exactly `i`. The **distance** between two numbers on the sequence, `a[i]` and `a[j]`, is the absolute difference of their indices, `|j - i|`. Return _the **lexicographically largest** sequence__. It is guaranteed that under the given constraints, there is always a solution._ A sequence `a` is lexicographically larger than a sequence `b` (of the same length) if in the first position where `a` and `b` differ, sequence `a` has a number greater than the corresponding number in `b`. For example, `[0,1,9,0]` is lexicographically larger than `[0,1,5,6]` because the first position they differ is at the third number, and `9` is greater than `5`. **Example 1:** **Input:** n = 3 **Output:** \[3,1,2,3,2\] **Explanation:** \[2,3,2,1,3\] is also a valid sequence, but \[3,1,2,3,2\] is the lexicographically largest valid sequence. **Example 2:** **Input:** n = 5 **Output:** \[5,3,1,4,3,5,2,4,2\] **Constraints:** * `1 <= n <= 20`
null
Python3 solution: ternary operators
construct-the-lexicographically-largest-valid-sequence
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nPut the integers in from left to right, and from large to small. Whenver we can fill the array, we have the answer\n# Approach\n<!-- Describe your approach to solving the problem. -->\nStandard backtracking. The answer is found whenever we reach the end\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nI tried larger $n$, and found that when $n$ is $39$, the calculation suddenly takes very long, probably because this is the first number in which the question setup breaks down.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n# Code\n```\n#\n# @lc app=leetcode id=1718 lang=python3\n#\n# [1718] Construct the Lexicographically Largest Valid Sequence\n#\n\n# @lc code=start\nfrom typing import List\n\n\nclass Solution:\n \'\'\'\n Put the integers in from left to right, and from large to small. Whenver we can fill the array, we have the answer\n \'\'\' \n\n def backtrack(self, i):\n if i == 2*self.n - 1:\n self.ans = [num for num in self.arr]\n return True\n elif self.arr[i] > 0:\n return self.backtrack(i + 1)\n else:\n for j in range(self.n, 0, -1):\n if j not in self.used and (i + j < 2*self.n - 1 if j > 1 else True) and self.arr[i] == 0 and (True if j == 1 else self.arr[i + j] == 0):\n self.used.add(j)\n self.arr[i] = j\n if j > 1:\n self.arr[i + j] = j\n if self.backtrack(i + 1):\n return True\n self.arr[i] = 0\n if j > 1:\n self.arr[i + j] = 0\n self.used.remove(j)\n return False\n\n\n def constructDistancedSequence(self, n: int) -> List[int]:\n self.arr = [0 for i in range(2*n - 1)]\n self.used = set()\n self.n = n\n self.ans = []\n found = self.backtrack(0)\n return self.ans\n \n\n \n# @lc code=end\n\n```
0
You are given an array `nums` that consists of positive integers. The **GCD** of a sequence of numbers is defined as the greatest integer that divides **all** the numbers in the sequence evenly. * For example, the GCD of the sequence `[4,6,16]` is `2`. A **subsequence** of an array is a sequence that can be formed by removing some elements (possibly none) of the array. * For example, `[2,5,10]` is a subsequence of `[1,2,1,**2**,4,1,**5**,**10**]`. Return _the **number** of **different** GCDs among all **non-empty** subsequences of_ `nums`. **Example 1:** **Input:** nums = \[6,10,3\] **Output:** 5 **Explanation:** The figure shows all the non-empty subsequences and their GCDs. The different GCDs are 6, 10, 3, 2, and 1. **Example 2:** **Input:** nums = \[5,15,40,5,6\] **Output:** 7 **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 2 * 105`
Heuristic algorithm may work.
Easy Python Solution Using Recursion
construct-the-lexicographically-largest-valid-sequence
0
1
# Code\n```\nclass Solution:\n def constructDistancedSequence(self, n: int) -> List[int]:\n arr=[-1 for _ in range(2*n-1)]\n status=self.get(arr,0,0,n)\n return arr\n def get(self,arr,i,bit,n):\n if(i>=len(arr)):\n return True\n elif(arr[i]!=-1):\n return self.get(arr,i+1,bit,n)\n else:\n for j in range(n,0,-1):\n if((bit>>j)&1!=0 or (j!=1 and ((j+i)>=len(arr) or arr[j+i]!=-1))):continue\n arr[i]=j\n if(j!=1):\n arr[i+j]=j\n status=self.get(arr,i+1,bit|(1<<j),n)\n if(status):return True\n arr[i]=-1\n if(j!=1):\n arr[i+j]=-1\n return False\n```
0
Given an integer `n`, find a sequence that satisfies all of the following: * The integer `1` occurs once in the sequence. * Each integer between `2` and `n` occurs twice in the sequence. * For every integer `i` between `2` and `n`, the **distance** between the two occurrences of `i` is exactly `i`. The **distance** between two numbers on the sequence, `a[i]` and `a[j]`, is the absolute difference of their indices, `|j - i|`. Return _the **lexicographically largest** sequence__. It is guaranteed that under the given constraints, there is always a solution._ A sequence `a` is lexicographically larger than a sequence `b` (of the same length) if in the first position where `a` and `b` differ, sequence `a` has a number greater than the corresponding number in `b`. For example, `[0,1,9,0]` is lexicographically larger than `[0,1,5,6]` because the first position they differ is at the third number, and `9` is greater than `5`. **Example 1:** **Input:** n = 3 **Output:** \[3,1,2,3,2\] **Explanation:** \[2,3,2,1,3\] is also a valid sequence, but \[3,1,2,3,2\] is the lexicographically largest valid sequence. **Example 2:** **Input:** n = 5 **Output:** \[5,3,1,4,3,5,2,4,2\] **Constraints:** * `1 <= n <= 20`
null
Easy Python Solution Using Recursion
construct-the-lexicographically-largest-valid-sequence
0
1
# Code\n```\nclass Solution:\n def constructDistancedSequence(self, n: int) -> List[int]:\n arr=[-1 for _ in range(2*n-1)]\n status=self.get(arr,0,0,n)\n return arr\n def get(self,arr,i,bit,n):\n if(i>=len(arr)):\n return True\n elif(arr[i]!=-1):\n return self.get(arr,i+1,bit,n)\n else:\n for j in range(n,0,-1):\n if((bit>>j)&1!=0 or (j!=1 and ((j+i)>=len(arr) or arr[j+i]!=-1))):continue\n arr[i]=j\n if(j!=1):\n arr[i+j]=j\n status=self.get(arr,i+1,bit|(1<<j),n)\n if(status):return True\n arr[i]=-1\n if(j!=1):\n arr[i+j]=-1\n return False\n```
0
You are given an array `nums` that consists of positive integers. The **GCD** of a sequence of numbers is defined as the greatest integer that divides **all** the numbers in the sequence evenly. * For example, the GCD of the sequence `[4,6,16]` is `2`. A **subsequence** of an array is a sequence that can be formed by removing some elements (possibly none) of the array. * For example, `[2,5,10]` is a subsequence of `[1,2,1,**2**,4,1,**5**,**10**]`. Return _the **number** of **different** GCDs among all **non-empty** subsequences of_ `nums`. **Example 1:** **Input:** nums = \[6,10,3\] **Output:** 5 **Explanation:** The figure shows all the non-empty subsequences and their GCDs. The different GCDs are 6, 10, 3, 2, and 1. **Example 2:** **Input:** nums = \[5,15,40,5,6\] **Output:** 7 **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 2 * 105`
Heuristic algorithm may work.
Python | Backtracking | Clean Code
construct-the-lexicographically-largest-valid-sequence
0
1
# Code\n```\nclass Solution:\n def constructDistancedSequence(self, n: int) -> List[int]:\n m = 2*n - 1\n A = [0]*m\n path = set()\n def dfs(i):\n if i == m:\n return all(A)\n if A[i]:\n return dfs(i+1)\n for v in range(n, 0, -1):\n j = i if v == 1 else i + v\n if v not in path and j < m and not A[j]:\n A[i], A[j] = v, v\n path.add(v)\n if dfs(i+1): return True\n A[i], A[j] = 0, 0\n path.remove(v)\n return False\n if dfs(0): return A\n return []\n\n```
0
Given an integer `n`, find a sequence that satisfies all of the following: * The integer `1` occurs once in the sequence. * Each integer between `2` and `n` occurs twice in the sequence. * For every integer `i` between `2` and `n`, the **distance** between the two occurrences of `i` is exactly `i`. The **distance** between two numbers on the sequence, `a[i]` and `a[j]`, is the absolute difference of their indices, `|j - i|`. Return _the **lexicographically largest** sequence__. It is guaranteed that under the given constraints, there is always a solution._ A sequence `a` is lexicographically larger than a sequence `b` (of the same length) if in the first position where `a` and `b` differ, sequence `a` has a number greater than the corresponding number in `b`. For example, `[0,1,9,0]` is lexicographically larger than `[0,1,5,6]` because the first position they differ is at the third number, and `9` is greater than `5`. **Example 1:** **Input:** n = 3 **Output:** \[3,1,2,3,2\] **Explanation:** \[2,3,2,1,3\] is also a valid sequence, but \[3,1,2,3,2\] is the lexicographically largest valid sequence. **Example 2:** **Input:** n = 5 **Output:** \[5,3,1,4,3,5,2,4,2\] **Constraints:** * `1 <= n <= 20`
null
Python | Backtracking | Clean Code
construct-the-lexicographically-largest-valid-sequence
0
1
# Code\n```\nclass Solution:\n def constructDistancedSequence(self, n: int) -> List[int]:\n m = 2*n - 1\n A = [0]*m\n path = set()\n def dfs(i):\n if i == m:\n return all(A)\n if A[i]:\n return dfs(i+1)\n for v in range(n, 0, -1):\n j = i if v == 1 else i + v\n if v not in path and j < m and not A[j]:\n A[i], A[j] = v, v\n path.add(v)\n if dfs(i+1): return True\n A[i], A[j] = 0, 0\n path.remove(v)\n return False\n if dfs(0): return A\n return []\n\n```
0
You are given an array `nums` that consists of positive integers. The **GCD** of a sequence of numbers is defined as the greatest integer that divides **all** the numbers in the sequence evenly. * For example, the GCD of the sequence `[4,6,16]` is `2`. A **subsequence** of an array is a sequence that can be formed by removing some elements (possibly none) of the array. * For example, `[2,5,10]` is a subsequence of `[1,2,1,**2**,4,1,**5**,**10**]`. Return _the **number** of **different** GCDs among all **non-empty** subsequences of_ `nums`. **Example 1:** **Input:** nums = \[6,10,3\] **Output:** 5 **Explanation:** The figure shows all the non-empty subsequences and their GCDs. The different GCDs are 6, 10, 3, 2, and 1. **Example 2:** **Input:** nums = \[5,15,40,5,6\] **Output:** 7 **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 2 * 105`
Heuristic algorithm may work.
Python3 DFS w/ backtracking
construct-the-lexicographically-largest-valid-sequence
0
1
# Intuition\nWe start with an array of all 0s of length $$2n - 1$$. Using depth first search we place the higher number possible in the first cell in the array that is a 0. We repeat this process until we\'ve either found a solution or there are no more possible placements, in which case we backtrack to the next possible previous move.\n\nThe first solution we find will have the highest possible lexicographical order as we are always inserting the highest possible number into the next available 0 slot.\n\n\n```\nclass Solution:\n def constructDistancedSequence(self, n: int) -> List[int]:\n def dfs(sequence):\n if 0 not in sequence:\n return sequence\n idx = sequence.index(0)\n\n for nextNum in range(n, 0, -1):\n nextIdx = idx + nextNum\n if nextNum == 1:\n nextIdx -= 1\n if nextNum in sequence or nextIdx >= len(sequence) or sequence[nextIdx] != 0:\n continue\n\n sequence[idx], sequence[nextIdx] = nextNum, nextNum\n res = dfs(sequence)\n if res != -1:\n return res\n sequence[idx], sequence[nextIdx] = 0, 0\n\n return -1\n\n return dfs([0] * (2 * n - 1))\n \n```
0
Given an integer `n`, find a sequence that satisfies all of the following: * The integer `1` occurs once in the sequence. * Each integer between `2` and `n` occurs twice in the sequence. * For every integer `i` between `2` and `n`, the **distance** between the two occurrences of `i` is exactly `i`. The **distance** between two numbers on the sequence, `a[i]` and `a[j]`, is the absolute difference of their indices, `|j - i|`. Return _the **lexicographically largest** sequence__. It is guaranteed that under the given constraints, there is always a solution._ A sequence `a` is lexicographically larger than a sequence `b` (of the same length) if in the first position where `a` and `b` differ, sequence `a` has a number greater than the corresponding number in `b`. For example, `[0,1,9,0]` is lexicographically larger than `[0,1,5,6]` because the first position they differ is at the third number, and `9` is greater than `5`. **Example 1:** **Input:** n = 3 **Output:** \[3,1,2,3,2\] **Explanation:** \[2,3,2,1,3\] is also a valid sequence, but \[3,1,2,3,2\] is the lexicographically largest valid sequence. **Example 2:** **Input:** n = 5 **Output:** \[5,3,1,4,3,5,2,4,2\] **Constraints:** * `1 <= n <= 20`
null
Python3 DFS w/ backtracking
construct-the-lexicographically-largest-valid-sequence
0
1
# Intuition\nWe start with an array of all 0s of length $$2n - 1$$. Using depth first search we place the higher number possible in the first cell in the array that is a 0. We repeat this process until we\'ve either found a solution or there are no more possible placements, in which case we backtrack to the next possible previous move.\n\nThe first solution we find will have the highest possible lexicographical order as we are always inserting the highest possible number into the next available 0 slot.\n\n\n```\nclass Solution:\n def constructDistancedSequence(self, n: int) -> List[int]:\n def dfs(sequence):\n if 0 not in sequence:\n return sequence\n idx = sequence.index(0)\n\n for nextNum in range(n, 0, -1):\n nextIdx = idx + nextNum\n if nextNum == 1:\n nextIdx -= 1\n if nextNum in sequence or nextIdx >= len(sequence) or sequence[nextIdx] != 0:\n continue\n\n sequence[idx], sequence[nextIdx] = nextNum, nextNum\n res = dfs(sequence)\n if res != -1:\n return res\n sequence[idx], sequence[nextIdx] = 0, 0\n\n return -1\n\n return dfs([0] * (2 * n - 1))\n \n```
0
You are given an array `nums` that consists of positive integers. The **GCD** of a sequence of numbers is defined as the greatest integer that divides **all** the numbers in the sequence evenly. * For example, the GCD of the sequence `[4,6,16]` is `2`. A **subsequence** of an array is a sequence that can be formed by removing some elements (possibly none) of the array. * For example, `[2,5,10]` is a subsequence of `[1,2,1,**2**,4,1,**5**,**10**]`. Return _the **number** of **different** GCDs among all **non-empty** subsequences of_ `nums`. **Example 1:** **Input:** nums = \[6,10,3\] **Output:** 5 **Explanation:** The figure shows all the non-empty subsequences and their GCDs. The different GCDs are 6, 10, 3, 2, and 1. **Example 2:** **Input:** nums = \[5,15,40,5,6\] **Output:** 7 **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 2 * 105`
Heuristic algorithm may work.
Python Backtracking Solution, Faster than 91%
construct-the-lexicographically-largest-valid-sequence
0
1
```\nclass Solution:\n def constructDistancedSequence(self, n: int) -> List[int]:\n ans, visited = [0] * (2 * n - 1), [False] * (n + 1)\n \n def backtrack(idx: int) -> bool:\n nonlocal ans, visited, n\n if idx == len(ans):\n return True\n if ans[idx] != 0:\n return backtrack(idx + 1)\n else:\n for num in range(n, 0, -1):\n if visited[num]:\n continue\n visited[num], ans[idx] = True, num\n if num == 1:\n if backtrack(idx + 1):\n return True\n elif idx + num < len(ans) and ans[idx + num] == 0:\n ans[num + idx] = num\n if backtrack(idx + 1): \n return True\n ans[idx + num] = 0\n ans[idx], visited[num] = 0, False\n return False\n \n backtrack(0)\n return ans\n```
0
Given an integer `n`, find a sequence that satisfies all of the following: * The integer `1` occurs once in the sequence. * Each integer between `2` and `n` occurs twice in the sequence. * For every integer `i` between `2` and `n`, the **distance** between the two occurrences of `i` is exactly `i`. The **distance** between two numbers on the sequence, `a[i]` and `a[j]`, is the absolute difference of their indices, `|j - i|`. Return _the **lexicographically largest** sequence__. It is guaranteed that under the given constraints, there is always a solution._ A sequence `a` is lexicographically larger than a sequence `b` (of the same length) if in the first position where `a` and `b` differ, sequence `a` has a number greater than the corresponding number in `b`. For example, `[0,1,9,0]` is lexicographically larger than `[0,1,5,6]` because the first position they differ is at the third number, and `9` is greater than `5`. **Example 1:** **Input:** n = 3 **Output:** \[3,1,2,3,2\] **Explanation:** \[2,3,2,1,3\] is also a valid sequence, but \[3,1,2,3,2\] is the lexicographically largest valid sequence. **Example 2:** **Input:** n = 5 **Output:** \[5,3,1,4,3,5,2,4,2\] **Constraints:** * `1 <= n <= 20`
null
Python Backtracking Solution, Faster than 91%
construct-the-lexicographically-largest-valid-sequence
0
1
```\nclass Solution:\n def constructDistancedSequence(self, n: int) -> List[int]:\n ans, visited = [0] * (2 * n - 1), [False] * (n + 1)\n \n def backtrack(idx: int) -> bool:\n nonlocal ans, visited, n\n if idx == len(ans):\n return True\n if ans[idx] != 0:\n return backtrack(idx + 1)\n else:\n for num in range(n, 0, -1):\n if visited[num]:\n continue\n visited[num], ans[idx] = True, num\n if num == 1:\n if backtrack(idx + 1):\n return True\n elif idx + num < len(ans) and ans[idx + num] == 0:\n ans[num + idx] = num\n if backtrack(idx + 1): \n return True\n ans[idx + num] = 0\n ans[idx], visited[num] = 0, False\n return False\n \n backtrack(0)\n return ans\n```
0
You are given an array `nums` that consists of positive integers. The **GCD** of a sequence of numbers is defined as the greatest integer that divides **all** the numbers in the sequence evenly. * For example, the GCD of the sequence `[4,6,16]` is `2`. A **subsequence** of an array is a sequence that can be formed by removing some elements (possibly none) of the array. * For example, `[2,5,10]` is a subsequence of `[1,2,1,**2**,4,1,**5**,**10**]`. Return _the **number** of **different** GCDs among all **non-empty** subsequences of_ `nums`. **Example 1:** **Input:** nums = \[6,10,3\] **Output:** 5 **Explanation:** The figure shows all the non-empty subsequences and their GCDs. The different GCDs are 6, 10, 3, 2, and 1. **Example 2:** **Input:** nums = \[5,15,40,5,6\] **Output:** 7 **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 2 * 105`
Heuristic algorithm may work.
[Python3] backtracking
construct-the-lexicographically-largest-valid-sequence
0
1
**Algo**\nThis a typical backtracking problem. Essentially, we have an array of `2*n-1` positions for which we progressively fill in numbers of `1, ..., n` of which `1` has multiplicity 1 and the others have 2. \n\nHere the strategy is that we aggresively fill in large numbers in high position if possible. \n\n**Implementation**\n```\nclass Solution:\n def constructDistancedSequence(self, n: int) -> List[int]:\n ans = [0]*(2*n-1)\n \n def fn(i): \n """Return largest sequence after filling in ith position."""\n if i == 2*n-1 or ans[i] and fn(i+1): return True \n for x in reversed(range(1, n+1)): \n if x not in ans: \n ii = x if x > 1 else 0 \n if i+ii < 2*n-1 and ans[i] == ans[i+ii] == 0: \n ans[i] = ans[i+ii] = x\n if fn(i+1): return True \n ans[i] = ans[i+ii] = 0 \n \n fn(0)\n return ans \n```
2
Given an integer `n`, find a sequence that satisfies all of the following: * The integer `1` occurs once in the sequence. * Each integer between `2` and `n` occurs twice in the sequence. * For every integer `i` between `2` and `n`, the **distance** between the two occurrences of `i` is exactly `i`. The **distance** between two numbers on the sequence, `a[i]` and `a[j]`, is the absolute difference of their indices, `|j - i|`. Return _the **lexicographically largest** sequence__. It is guaranteed that under the given constraints, there is always a solution._ A sequence `a` is lexicographically larger than a sequence `b` (of the same length) if in the first position where `a` and `b` differ, sequence `a` has a number greater than the corresponding number in `b`. For example, `[0,1,9,0]` is lexicographically larger than `[0,1,5,6]` because the first position they differ is at the third number, and `9` is greater than `5`. **Example 1:** **Input:** n = 3 **Output:** \[3,1,2,3,2\] **Explanation:** \[2,3,2,1,3\] is also a valid sequence, but \[3,1,2,3,2\] is the lexicographically largest valid sequence. **Example 2:** **Input:** n = 5 **Output:** \[5,3,1,4,3,5,2,4,2\] **Constraints:** * `1 <= n <= 20`
null
[Python3] backtracking
construct-the-lexicographically-largest-valid-sequence
0
1
**Algo**\nThis a typical backtracking problem. Essentially, we have an array of `2*n-1` positions for which we progressively fill in numbers of `1, ..., n` of which `1` has multiplicity 1 and the others have 2. \n\nHere the strategy is that we aggresively fill in large numbers in high position if possible. \n\n**Implementation**\n```\nclass Solution:\n def constructDistancedSequence(self, n: int) -> List[int]:\n ans = [0]*(2*n-1)\n \n def fn(i): \n """Return largest sequence after filling in ith position."""\n if i == 2*n-1 or ans[i] and fn(i+1): return True \n for x in reversed(range(1, n+1)): \n if x not in ans: \n ii = x if x > 1 else 0 \n if i+ii < 2*n-1 and ans[i] == ans[i+ii] == 0: \n ans[i] = ans[i+ii] = x\n if fn(i+1): return True \n ans[i] = ans[i+ii] = 0 \n \n fn(0)\n return ans \n```
2
You are given an array `nums` that consists of positive integers. The **GCD** of a sequence of numbers is defined as the greatest integer that divides **all** the numbers in the sequence evenly. * For example, the GCD of the sequence `[4,6,16]` is `2`. A **subsequence** of an array is a sequence that can be formed by removing some elements (possibly none) of the array. * For example, `[2,5,10]` is a subsequence of `[1,2,1,**2**,4,1,**5**,**10**]`. Return _the **number** of **different** GCDs among all **non-empty** subsequences of_ `nums`. **Example 1:** **Input:** nums = \[6,10,3\] **Output:** 5 **Explanation:** The figure shows all the non-empty subsequences and their GCDs. The different GCDs are 6, 10, 3, 2, and 1. **Example 2:** **Input:** nums = \[5,15,40,5,6\] **Output:** 7 **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 2 * 105`
Heuristic algorithm may work.
Python | DFS | Backtracking
construct-the-lexicographically-largest-valid-sequence
0
1
```\nclass Solution:\n def constructDistancedSequence(self, n: int) -> List[int]:\n arr=[0]*((n*2)-1)\n self.ans=None\n def dfs(arr,i):\n for num in range(n,0,-1):#Traverse Reverse as we need highest lexicographic number\n if num not in arr:\n if num==1:\n if arr[i]!=0:#place is occupied\n continue\n else:#Occupy the one place\n arr[i]=1\n else:\n if arr[i]!=0 or (i+num)>=len(arr) or arr[i+num]!=0:#place is occupied or invalid\n continue\n else:#Occupy the two place\n arr[i]=num\n arr[i+num]=num\n if 0 in arr:#means few places are still vacant\n if dfs(arr,arr.index(0)):\n return True\n if arr[i]==1:#Backtracking vacate the one place\n arr[i]=0\n else:#Backtracking vacate both the two occupied place\n arr[i]=0\n arr[i+num]=0\n else:#Yay no place is vacant \n self.ans=arr\n return True\n \n dfs(arr,0)\n return self.ans\n```
1
Given an integer `n`, find a sequence that satisfies all of the following: * The integer `1` occurs once in the sequence. * Each integer between `2` and `n` occurs twice in the sequence. * For every integer `i` between `2` and `n`, the **distance** between the two occurrences of `i` is exactly `i`. The **distance** between two numbers on the sequence, `a[i]` and `a[j]`, is the absolute difference of their indices, `|j - i|`. Return _the **lexicographically largest** sequence__. It is guaranteed that under the given constraints, there is always a solution._ A sequence `a` is lexicographically larger than a sequence `b` (of the same length) if in the first position where `a` and `b` differ, sequence `a` has a number greater than the corresponding number in `b`. For example, `[0,1,9,0]` is lexicographically larger than `[0,1,5,6]` because the first position they differ is at the third number, and `9` is greater than `5`. **Example 1:** **Input:** n = 3 **Output:** \[3,1,2,3,2\] **Explanation:** \[2,3,2,1,3\] is also a valid sequence, but \[3,1,2,3,2\] is the lexicographically largest valid sequence. **Example 2:** **Input:** n = 5 **Output:** \[5,3,1,4,3,5,2,4,2\] **Constraints:** * `1 <= n <= 20`
null
Python | DFS | Backtracking
construct-the-lexicographically-largest-valid-sequence
0
1
```\nclass Solution:\n def constructDistancedSequence(self, n: int) -> List[int]:\n arr=[0]*((n*2)-1)\n self.ans=None\n def dfs(arr,i):\n for num in range(n,0,-1):#Traverse Reverse as we need highest lexicographic number\n if num not in arr:\n if num==1:\n if arr[i]!=0:#place is occupied\n continue\n else:#Occupy the one place\n arr[i]=1\n else:\n if arr[i]!=0 or (i+num)>=len(arr) or arr[i+num]!=0:#place is occupied or invalid\n continue\n else:#Occupy the two place\n arr[i]=num\n arr[i+num]=num\n if 0 in arr:#means few places are still vacant\n if dfs(arr,arr.index(0)):\n return True\n if arr[i]==1:#Backtracking vacate the one place\n arr[i]=0\n else:#Backtracking vacate both the two occupied place\n arr[i]=0\n arr[i+num]=0\n else:#Yay no place is vacant \n self.ans=arr\n return True\n \n dfs(arr,0)\n return self.ans\n```
1
You are given an array `nums` that consists of positive integers. The **GCD** of a sequence of numbers is defined as the greatest integer that divides **all** the numbers in the sequence evenly. * For example, the GCD of the sequence `[4,6,16]` is `2`. A **subsequence** of an array is a sequence that can be formed by removing some elements (possibly none) of the array. * For example, `[2,5,10]` is a subsequence of `[1,2,1,**2**,4,1,**5**,**10**]`. Return _the **number** of **different** GCDs among all **non-empty** subsequences of_ `nums`. **Example 1:** **Input:** nums = \[6,10,3\] **Output:** 5 **Explanation:** The figure shows all the non-empty subsequences and their GCDs. The different GCDs are 6, 10, 3, 2, and 1. **Example 2:** **Input:** nums = \[5,15,40,5,6\] **Output:** 7 **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 2 * 105`
Heuristic algorithm may work.
[Python3] greedy
number-of-ways-to-reconstruct-a-tree
0
1
\n```\nclass Solution:\n def checkWays(self, pairs: List[List[int]]) -> int:\n graph = {}\n for x, y in pairs: \n graph.setdefault(x, set()).add(y)\n graph.setdefault(y, set()).add(x)\n \n ans = 1 \n ancestors = set()\n for n in sorted(graph, key=lambda x: len(graph[x]), reverse=True): \n p = min(ancestors & graph[n], key=lambda x: len(graph[x]), default=None) # immediate ancestor \n ancestors.add(n)\n if p: \n if graph[n] - (graph[p] | {p}): return 0 # impossible to have more than ancestor\n if len(graph[n]) == len(graph[p]): ans = 2\n elif len(graph[n]) != len(graph)-1: return 0\n return ans \n```\n\n```\nclass Solution:\n def checkWays(self, pairs: List[List[int]]) -> int:\n nodes = set()\n graph = {}\n degree = {}\n for x, y in pairs: \n nodes |= {x, y}\n graph.setdefault(x, set()).add(y)\n graph.setdefault(y, set()).add(x)\n degree[x] = 1 + degree.get(x, 0)\n degree[y] = 1 + degree.get(y, 0)\n \n if max(degree.values()) < len(nodes) - 1: return 0 # no root\n for n in nodes: \n if degree[n] < len(nodes)-1: \n nei = set()\n for nn in graph[n]: \n if degree[n] >= degree[nn]: nei |= graph[nn] # brothers & childrens\n if nei - {n} - graph[n]: return 0 # impossible\n \n for n in nodes: \n if any(degree[n] == degree[nn] for nn in graph[n]): return 2 # brothers \n return 1 \n```
5
You are given an array `pairs`, where `pairs[i] = [xi, yi]`, and: * There are no duplicates. * `xi < yi` Let `ways` be the number of rooted trees that satisfy the following conditions: * The tree consists of nodes whose values appeared in `pairs`. * A pair `[xi, yi]` exists in `pairs` **if and only if** `xi` is an ancestor of `yi` or `yi` is an ancestor of `xi`. * **Note:** the tree does not have to be a binary tree. Two ways are considered to be different if there is at least one node that has different parents in both ways. Return: * `0` if `ways == 0` * `1` if `ways == 1` * `2` if `ways > 1` A **rooted tree** is a tree that has a single root node, and all edges are oriented to be outgoing from the root. An **ancestor** of a node is any node on the path from the root to that node (excluding the node itself). The root has no ancestors. **Example 1:** **Input:** pairs = \[\[1,2\],\[2,3\]\] **Output:** 1 **Explanation:** There is exactly one valid rooted tree, which is shown in the above figure. **Example 2:** **Input:** pairs = \[\[1,2\],\[2,3\],\[1,3\]\] **Output:** 2 **Explanation:** There are multiple valid rooted trees. Three of them are shown in the above figures. **Example 3:** **Input:** pairs = \[\[1,2\],\[2,3\],\[2,4\],\[1,5\]\] **Output:** 0 **Explanation:** There are no valid rooted trees. **Constraints:** * `1 <= pairs.length <= 105` * `1 <= xi < yi <= 500` * The elements in `pairs` are unique.
Try to put at least one box in the house pushing it from either side. Once you put one box to the house, you can solve the problem with the same logic used to solve version I. You have a warehouse open from the left only and a warehouse open from the right only.
[Python3] greedy
number-of-ways-to-reconstruct-a-tree
0
1
\n```\nclass Solution:\n def checkWays(self, pairs: List[List[int]]) -> int:\n graph = {}\n for x, y in pairs: \n graph.setdefault(x, set()).add(y)\n graph.setdefault(y, set()).add(x)\n \n ans = 1 \n ancestors = set()\n for n in sorted(graph, key=lambda x: len(graph[x]), reverse=True): \n p = min(ancestors & graph[n], key=lambda x: len(graph[x]), default=None) # immediate ancestor \n ancestors.add(n)\n if p: \n if graph[n] - (graph[p] | {p}): return 0 # impossible to have more than ancestor\n if len(graph[n]) == len(graph[p]): ans = 2\n elif len(graph[n]) != len(graph)-1: return 0\n return ans \n```\n\n```\nclass Solution:\n def checkWays(self, pairs: List[List[int]]) -> int:\n nodes = set()\n graph = {}\n degree = {}\n for x, y in pairs: \n nodes |= {x, y}\n graph.setdefault(x, set()).add(y)\n graph.setdefault(y, set()).add(x)\n degree[x] = 1 + degree.get(x, 0)\n degree[y] = 1 + degree.get(y, 0)\n \n if max(degree.values()) < len(nodes) - 1: return 0 # no root\n for n in nodes: \n if degree[n] < len(nodes)-1: \n nei = set()\n for nn in graph[n]: \n if degree[n] >= degree[nn]: nei |= graph[nn] # brothers & childrens\n if nei - {n} - graph[n]: return 0 # impossible\n \n for n in nodes: \n if any(degree[n] == degree[nn] for nn in graph[n]): return 2 # brothers \n return 1 \n```
5
There are `m` boys and `n` girls in a class attending an upcoming party. You are given an `m x n` integer matrix `grid`, where `grid[i][j]` equals `0` or `1`. If `grid[i][j] == 1`, then that means the `ith` boy can invite the `jth` girl to the party. A boy can invite at most **one girl**, and a girl can accept at most **one invitation** from a boy. Return _the **maximum** possible number of accepted invitations._ **Example 1:** **Input:** grid = \[\[1,1,1\], \[1,0,1\], \[0,0,1\]\] **Output:** 3 **Explanation:** The invitations are sent as follows: - The 1st boy invites the 2nd girl. - The 2nd boy invites the 1st girl. - The 3rd boy invites the 3rd girl. **Example 2:** **Input:** grid = \[\[1,0,1,0\], \[1,0,0,0\], \[0,0,1,0\], \[1,1,1,0\]\] **Output:** 3 **Explanation:** The invitations are sent as follows: -The 1st boy invites the 3rd girl. -The 2nd boy invites the 1st girl. -The 3rd boy invites no one. -The 4th boy invites the 2nd girl. **Constraints:** * `grid.length == m` * `grid[i].length == n` * `1 <= m, n <= 200` * `grid[i][j]` is either `0` or `1`.
Think inductively. The first step is to get the root. Obviously, the root should be in pairs with all the nodes. If there isn't exactly one such node, then there are 0 ways. The number of pairs involving a node must be less than or equal to that number of its parent. Actually, if it's equal, then there is not exactly 1 way, because they can be swapped. Recursively, given a set of nodes, get the node with the most pairs, then this must be a root and have no parents in the current set of nodes.
SOLID Principles | Abstracting the DSU possibilities | Commented and Explained | 100% run time
number-of-ways-to-reconstruct-a-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis question is basically asking for a subset of the disjointed set union of the nodes in the graph to be a tree. This can be abstracted out by simple comparisons of the number of neighbors, and whether or not a specific node has neighbors that are not part of its parents neighbors or the parent itself. This is basically asking if the node has neighbors not a part of its parents grouping in a disjoint union set. \n\nBased on that we can utilize a graphical approach to determine whether or not a set of subtrees are possible as follows\n\nAt initialization, we want to set up our graph, our ancestors set, and our rank needed. Graph is a defaultdict of sets, ancestors are just a set, and rank needed starts at 0. \n\nThen, we set up a function to add an edge to the graph given a source and destination. Since this is a bidirectional graph, we simply add it in both directions and return. \n\nThen we set up a build graph from edges function that will loop over a list of edges in a for each pattern. As it does \n- call the add edge function passing the unpacked edge \n\nFrom here we have to consider how we can associate ranks and unions in the graph. Ranks are the number of neighbors usually in a dsu after unioning. Unions involve the question of neighbors being associated in the same group. \n\nBased on these two ideas, we will need functions to get the node rank, to sort the graph keys by the number of neighbors, and to get the immediate ancestor of a graph key as the union of the ancestors and a node where we hunt for the minimal. \n\nWe want the node rank for comparisons later, and you can pass it as a comparitor function if you want for the sorting of the graph. I chose not to for readability. \n\nWe want to be able to get the immediate ancestor as the set of ancestors unioned with this nodes neighbor as the minimal, so we can always get the minimal of the ancestors so we know which group we are a part of if we are a sub root, or if we are a potential root node. \n\nNow we need to process our graph\nWe will want it to be sorted, and the result of our processing should be our answer on number of ways. Based on this set up ways as 1 and set up a for loop to loop over the sorted version of the keys of the graph. As we do\n- add this node to the ancestors \n- get this nodes rank \n- get this nodes parent (immediate ancestor) \n- if parent is None, we have a potential root node \n - if the potential root node does not have a rank equal to the number of nodes minus 1, we cannot place a tree here ever, return 0 \n - otherwise, continue to next instance \n- if parent is not none, we are now processing non potential root nodes\n - in that case, get the rank of the parent \n - if the set difference of the nodes neighbors with either the neighbors of the parent or just the parent istelf is greater than 0, we have an instance of a child not having been a part of its parent group, and can return 0 \n - otherwise, if the node rank is the parent rank, we have at least two instances of a sub tree forming. Set ways to 2 and continue. \nWhen done, return the ways found \n\nOur check ways function then simply builds the graph with the edges and then returns the result of a call to process sorted graph \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe utilize an object oriented approach here where we attempt to split the functionalities needed for a single responsibility as much as necessary. We also utilize an understanding of disjoint set union, where we are actually considering the possibility of forming such a thing for the graph without having to actually form the many forms of such a thing for the graph. As such, we have abstracted out the possibilities of the DSU. Furthermore, we utilize early quitting in the main program to allow us to stop at the earliest possible point. This does run the cost of sorting however, which in this case is V log V \n\n# Complexity\n- Time complexity: O( max (V log V + E, V * (n-1)/2 + E))\n - O(V log V) for sorting the graph nodes \n - O(E) for building the edges of the graph \n - O(V) for processing the sorted graph\n - where inside this we incur O(N) as the cost of our potential difference finding operation. If we did this as much as possible, we would have O(V * N). However, if such a case were to occur, we would actually stop sooner (as it would then indicate a cyclic presence!). As such, we can content ourself to the lower bound of O(V * (n-1)/2), as we will reduce in the number of neighbors as we go, and as n is less than V at all times. \n\n- Space complexity: O( E * V )\n - We end up storing every edge for every node, so O ( E * V )\n\n# Code\n```\nclass Solution:\n # initialization \n def __init__(self) : \n self.graph = collections.defaultdict(set)\n self.ancestors = set()\n self.rank_needed = 0\n\n # add edge to graph \n def add_edge(self, source, dest) : \n self.graph[source].add(dest)\n self.graph[dest].add(source)\n\n # build graph from a list of edges \n def build_graph_from_edges(self, edges) :\n # loop over edges \n for edge in edges :\n # call build with unpacked edge \n self.add_edge(*edge)\n # when done, set rank needed \n self.rank_needed = len(self.graph) - 1\n \n # return the node rank of a node in our graph as the length of the neighbors \n def get_node_rank(self, node_id) : \n return len(self.graph[node_id])\n\n # get a sorted version of the graph from greatest to least neighbors \n def get_sorted_graph(self) : \n return sorted(self.graph, key=lambda node_id : len(self.graph[node_id]), reverse=True)\n\n # get the immediate ancestor of our given node by \n # taking the union of the ancestors so far with the neighbors of the given node \n # as the minmal of the sorted list of intersections based on the size of the neighbors \n def get_immediate_ancestor(self, node_id) : \n return min(self.ancestors & self.graph[node_id], key = lambda node_id : len(self.graph[node_id]), default=None)\n\n # process a sorted version of the graph for the given problem\n def process_sorted_graph(self) : \n # what we are asked to find \n ways = 1 \n # sort the nodes by number of neighbors for faster run time \n for node in self.get_sorted_graph(): \n # add this node to our set of ancestors in case we need them later \n self.ancestors.add(node)\n # get this nodes rank \n node_rank = self.get_node_rank(node)\n # get the immediate ancestor, aka parent \n parent = self.get_immediate_ancestor(node)\n # if you did not get the immediate ancestor, we may have a problem \n if parent is None : \n # if we did not have an immediate ancestor and we are not a possible root\n if node_rank != self.rank_needed : \n # then this precludes there ever being a return that is not 0 \n return 0\n else : \n # otherwise, keep going to other nodes, this might just be a child \n continue\n else : \n # if parent is not None \n # get parent rank for comparisons between the two \n parent_rank = self.get_node_rank(parent)\n # if the set difference of the neighbors of node with either the neighbors of parent or the parent itself is not 0\n # then we have a situation where we do not have a tree line. As soon as one case shows this, none are possible, so return 0 \n if self.graph[node] - (self.graph[parent] | {parent}): return 0 \n # otherwise, if the length of the neighbors of node matches the length of the neighbors of parent, \n # we have two possibilities for the root and can set ways to 2 for now. We may run across a case later that negates this \n if node_rank == parent_rank: ways = 2\n # if you have not returned yet, return ways. It is either 2 or 1. \n return ways \n\n def checkWays(self, pairs: List[List[int]]) -> int:\n # build graph function for bidirectional \n self.build_graph_from_edges(pairs)\n # return the result of processing the sorted graph \n return self.process_sorted_graph()\n```
1
You are given an array `pairs`, where `pairs[i] = [xi, yi]`, and: * There are no duplicates. * `xi < yi` Let `ways` be the number of rooted trees that satisfy the following conditions: * The tree consists of nodes whose values appeared in `pairs`. * A pair `[xi, yi]` exists in `pairs` **if and only if** `xi` is an ancestor of `yi` or `yi` is an ancestor of `xi`. * **Note:** the tree does not have to be a binary tree. Two ways are considered to be different if there is at least one node that has different parents in both ways. Return: * `0` if `ways == 0` * `1` if `ways == 1` * `2` if `ways > 1` A **rooted tree** is a tree that has a single root node, and all edges are oriented to be outgoing from the root. An **ancestor** of a node is any node on the path from the root to that node (excluding the node itself). The root has no ancestors. **Example 1:** **Input:** pairs = \[\[1,2\],\[2,3\]\] **Output:** 1 **Explanation:** There is exactly one valid rooted tree, which is shown in the above figure. **Example 2:** **Input:** pairs = \[\[1,2\],\[2,3\],\[1,3\]\] **Output:** 2 **Explanation:** There are multiple valid rooted trees. Three of them are shown in the above figures. **Example 3:** **Input:** pairs = \[\[1,2\],\[2,3\],\[2,4\],\[1,5\]\] **Output:** 0 **Explanation:** There are no valid rooted trees. **Constraints:** * `1 <= pairs.length <= 105` * `1 <= xi < yi <= 500` * The elements in `pairs` are unique.
Try to put at least one box in the house pushing it from either side. Once you put one box to the house, you can solve the problem with the same logic used to solve version I. You have a warehouse open from the left only and a warehouse open from the right only.
SOLID Principles | Abstracting the DSU possibilities | Commented and Explained | 100% run time
number-of-ways-to-reconstruct-a-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis question is basically asking for a subset of the disjointed set union of the nodes in the graph to be a tree. This can be abstracted out by simple comparisons of the number of neighbors, and whether or not a specific node has neighbors that are not part of its parents neighbors or the parent itself. This is basically asking if the node has neighbors not a part of its parents grouping in a disjoint union set. \n\nBased on that we can utilize a graphical approach to determine whether or not a set of subtrees are possible as follows\n\nAt initialization, we want to set up our graph, our ancestors set, and our rank needed. Graph is a defaultdict of sets, ancestors are just a set, and rank needed starts at 0. \n\nThen, we set up a function to add an edge to the graph given a source and destination. Since this is a bidirectional graph, we simply add it in both directions and return. \n\nThen we set up a build graph from edges function that will loop over a list of edges in a for each pattern. As it does \n- call the add edge function passing the unpacked edge \n\nFrom here we have to consider how we can associate ranks and unions in the graph. Ranks are the number of neighbors usually in a dsu after unioning. Unions involve the question of neighbors being associated in the same group. \n\nBased on these two ideas, we will need functions to get the node rank, to sort the graph keys by the number of neighbors, and to get the immediate ancestor of a graph key as the union of the ancestors and a node where we hunt for the minimal. \n\nWe want the node rank for comparisons later, and you can pass it as a comparitor function if you want for the sorting of the graph. I chose not to for readability. \n\nWe want to be able to get the immediate ancestor as the set of ancestors unioned with this nodes neighbor as the minimal, so we can always get the minimal of the ancestors so we know which group we are a part of if we are a sub root, or if we are a potential root node. \n\nNow we need to process our graph\nWe will want it to be sorted, and the result of our processing should be our answer on number of ways. Based on this set up ways as 1 and set up a for loop to loop over the sorted version of the keys of the graph. As we do\n- add this node to the ancestors \n- get this nodes rank \n- get this nodes parent (immediate ancestor) \n- if parent is None, we have a potential root node \n - if the potential root node does not have a rank equal to the number of nodes minus 1, we cannot place a tree here ever, return 0 \n - otherwise, continue to next instance \n- if parent is not none, we are now processing non potential root nodes\n - in that case, get the rank of the parent \n - if the set difference of the nodes neighbors with either the neighbors of the parent or just the parent istelf is greater than 0, we have an instance of a child not having been a part of its parent group, and can return 0 \n - otherwise, if the node rank is the parent rank, we have at least two instances of a sub tree forming. Set ways to 2 and continue. \nWhen done, return the ways found \n\nOur check ways function then simply builds the graph with the edges and then returns the result of a call to process sorted graph \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe utilize an object oriented approach here where we attempt to split the functionalities needed for a single responsibility as much as necessary. We also utilize an understanding of disjoint set union, where we are actually considering the possibility of forming such a thing for the graph without having to actually form the many forms of such a thing for the graph. As such, we have abstracted out the possibilities of the DSU. Furthermore, we utilize early quitting in the main program to allow us to stop at the earliest possible point. This does run the cost of sorting however, which in this case is V log V \n\n# Complexity\n- Time complexity: O( max (V log V + E, V * (n-1)/2 + E))\n - O(V log V) for sorting the graph nodes \n - O(E) for building the edges of the graph \n - O(V) for processing the sorted graph\n - where inside this we incur O(N) as the cost of our potential difference finding operation. If we did this as much as possible, we would have O(V * N). However, if such a case were to occur, we would actually stop sooner (as it would then indicate a cyclic presence!). As such, we can content ourself to the lower bound of O(V * (n-1)/2), as we will reduce in the number of neighbors as we go, and as n is less than V at all times. \n\n- Space complexity: O( E * V )\n - We end up storing every edge for every node, so O ( E * V )\n\n# Code\n```\nclass Solution:\n # initialization \n def __init__(self) : \n self.graph = collections.defaultdict(set)\n self.ancestors = set()\n self.rank_needed = 0\n\n # add edge to graph \n def add_edge(self, source, dest) : \n self.graph[source].add(dest)\n self.graph[dest].add(source)\n\n # build graph from a list of edges \n def build_graph_from_edges(self, edges) :\n # loop over edges \n for edge in edges :\n # call build with unpacked edge \n self.add_edge(*edge)\n # when done, set rank needed \n self.rank_needed = len(self.graph) - 1\n \n # return the node rank of a node in our graph as the length of the neighbors \n def get_node_rank(self, node_id) : \n return len(self.graph[node_id])\n\n # get a sorted version of the graph from greatest to least neighbors \n def get_sorted_graph(self) : \n return sorted(self.graph, key=lambda node_id : len(self.graph[node_id]), reverse=True)\n\n # get the immediate ancestor of our given node by \n # taking the union of the ancestors so far with the neighbors of the given node \n # as the minmal of the sorted list of intersections based on the size of the neighbors \n def get_immediate_ancestor(self, node_id) : \n return min(self.ancestors & self.graph[node_id], key = lambda node_id : len(self.graph[node_id]), default=None)\n\n # process a sorted version of the graph for the given problem\n def process_sorted_graph(self) : \n # what we are asked to find \n ways = 1 \n # sort the nodes by number of neighbors for faster run time \n for node in self.get_sorted_graph(): \n # add this node to our set of ancestors in case we need them later \n self.ancestors.add(node)\n # get this nodes rank \n node_rank = self.get_node_rank(node)\n # get the immediate ancestor, aka parent \n parent = self.get_immediate_ancestor(node)\n # if you did not get the immediate ancestor, we may have a problem \n if parent is None : \n # if we did not have an immediate ancestor and we are not a possible root\n if node_rank != self.rank_needed : \n # then this precludes there ever being a return that is not 0 \n return 0\n else : \n # otherwise, keep going to other nodes, this might just be a child \n continue\n else : \n # if parent is not None \n # get parent rank for comparisons between the two \n parent_rank = self.get_node_rank(parent)\n # if the set difference of the neighbors of node with either the neighbors of parent or the parent itself is not 0\n # then we have a situation where we do not have a tree line. As soon as one case shows this, none are possible, so return 0 \n if self.graph[node] - (self.graph[parent] | {parent}): return 0 \n # otherwise, if the length of the neighbors of node matches the length of the neighbors of parent, \n # we have two possibilities for the root and can set ways to 2 for now. We may run across a case later that negates this \n if node_rank == parent_rank: ways = 2\n # if you have not returned yet, return ways. It is either 2 or 1. \n return ways \n\n def checkWays(self, pairs: List[List[int]]) -> int:\n # build graph function for bidirectional \n self.build_graph_from_edges(pairs)\n # return the result of processing the sorted graph \n return self.process_sorted_graph()\n```
1
There are `m` boys and `n` girls in a class attending an upcoming party. You are given an `m x n` integer matrix `grid`, where `grid[i][j]` equals `0` or `1`. If `grid[i][j] == 1`, then that means the `ith` boy can invite the `jth` girl to the party. A boy can invite at most **one girl**, and a girl can accept at most **one invitation** from a boy. Return _the **maximum** possible number of accepted invitations._ **Example 1:** **Input:** grid = \[\[1,1,1\], \[1,0,1\], \[0,0,1\]\] **Output:** 3 **Explanation:** The invitations are sent as follows: - The 1st boy invites the 2nd girl. - The 2nd boy invites the 1st girl. - The 3rd boy invites the 3rd girl. **Example 2:** **Input:** grid = \[\[1,0,1,0\], \[1,0,0,0\], \[0,0,1,0\], \[1,1,1,0\]\] **Output:** 3 **Explanation:** The invitations are sent as follows: -The 1st boy invites the 3rd girl. -The 2nd boy invites the 1st girl. -The 3rd boy invites no one. -The 4th boy invites the 2nd girl. **Constraints:** * `grid.length == m` * `grid[i].length == n` * `1 <= m, n <= 200` * `grid[i][j]` is either `0` or `1`.
Think inductively. The first step is to get the root. Obviously, the root should be in pairs with all the nodes. If there isn't exactly one such node, then there are 0 ways. The number of pairs involving a node must be less than or equal to that number of its parent. Actually, if it's equal, then there is not exactly 1 way, because they can be swapped. Recursively, given a set of nodes, get the node with the most pairs, then this must be a root and have no parents in the current set of nodes.