question_slug
stringlengths 3
77
| title
stringlengths 1
183
| slug
stringlengths 12
45
| summary
stringlengths 1
160
⌀ | author
stringlengths 2
30
| certification
stringclasses 2
values | created_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| updated_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| hit_count
int64 0
10.6M
| has_video
bool 2
classes | content
stringlengths 4
576k
| upvotes
int64 0
11.5k
| downvotes
int64 0
358
| tags
stringlengths 2
193
| comments
int64 0
2.56k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
number-of-unique-good-subsequences
|
Count Distinct Subsequences check if 01 or 00 seen
|
count-distinct-subsequences-check-if-01-kdixs
|
\nclass Solution:\n def numberOfUniqueGoodSubsequences(self, binary: str) -> int:\n M = 10 ** 9 + 7\n n = len(binary)\n dp = [1] * (n +
|
theabbie
|
NORMAL
|
2024-02-05T04:34:21.787172+00:00
|
2024-02-05T04:34:21.787219+00:00
| 5 | false |
```\nclass Solution:\n def numberOfUniqueGoodSubsequences(self, binary: str) -> int:\n M = 10 ** 9 + 7\n n = len(binary)\n dp = [1] * (n + 1)\n prev = {}\n zerozero = False\n zeroone = False\n for i in range(1, n + 1):\n dp[i] = 2 * dp[i - 1]\n if binary[i - 1] in prev:\n dp[i] -= dp[prev[binary[i - 1]]]\n if "0" in prev:\n if binary[i - 1] == "0" and not zerozero:\n dp[i] -= 1\n zerozero = True\n if binary[i - 1] == "1" and not zeroone:\n dp[i] -= 1\n zeroone = True\n dp[i] %= M\n prev[binary[i - 1]] = i - 1\n dp[n] = (M + dp[n] - 1) % M\n \xA0 \xA0 \xA0 \xA0return dp[n] \n```
| 0 | 0 |
[]
| 0 |
number-of-unique-good-subsequences
|
a
|
a-by-user3043sb-wnkw
|
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
|
user3043SB
|
NORMAL
|
2024-01-12T21:13:10.523006+00:00
|
2024-01-12T21:13:10.523037+00:00
| 4 | false |
# 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```\nimport java.util.*;\n\n\npublic class Solution {\n\n // separate [0] as sequence and only count those without starting 0\n // after that the first 1 MUST be taken\n // finally count UNIQUE sequences only!!!!!!\n // use same approach as before: group by the ending digit so:\n // 101\n // 113 ending at 1 11 101\n // 124 total\n public int numberOfUniqueGoodSubsequences(String s) {\n int n = s.length();\n int i = 0;\n while (i < n && s.charAt(i) == \'0\') i++;\n boolean hasZero = i > 0; // skip the first 1\n if (i ==n) return 1; // only 0s\n\n i++; // skip the first one and pretend it is ""; then manually adjust the calculation for every next 1 to allow starting new seq\n long numEnding0 = 0;\n long numEnding1 = 1;\n long total = 1;\n for (; i < n; i++) {\n if (s.charAt(i) == \'0\') {\n hasZero = true;\n long newlyAdded = (total - numEnding0 + M) % M;\n numEnding0 = total; // +=(total - prevNumEnding0) = numEnding0 + total - numEnding0 = total\n total = (total + newlyAdded) % M; // total + newlyAdded\n } else {\n long newlyAdded = (total - numEnding1 + M + 1) % M; // +1 \n numEnding1 = (total + 1) % M; // +1 to manually adjust the calculation for every next 1 to allow starting new seq\n total = (total + newlyAdded) % M; // total + newlyAdded\n }\n }\n\n return (int) ((total + (hasZero ? 1 : 0)) % M);\n }\n\n int M = (int) 1e9 + 7;\n\n}\n\n\n```
| 0 | 0 |
['Java']
| 0 |
number-of-unique-good-subsequences
|
O(n) solution 68ms Beats 80.00% of users with JavaScript
|
on-solution-68ms-beats-8000-of-users-wit-1w55
|
Intuition\nThe code is designed to count the number of unique good subsequences in a binary string. A good subsequence is one that starts with \'1\' and ends wi
|
TrianePeart
|
NORMAL
|
2023-10-27T21:06:47.334990+00:00
|
2023-10-27T21:07:22.452872+00:00
| 19 | false |
# Intuition\nThe code is designed to count the number of unique good subsequences in a binary string. A good subsequence is one that starts with \'1\' and ends with \'0\'. It uses dynamic programming to efficiently track the counts of such subsequences ending with \'0\' and \'1\'. The presence of \'0\' is important, and if it is found in the string, an extra count of 1 is added to account for the subsequence \'0\'. By iteratively processing the characters, the code calculates the result modulo 10^9 + 7 to prevent integer overflow. \n\n# Approach\n\n\nInitialize two counters, endsWithZero and endsWithOne, to track the counts of good subsequences ending with \'0\' and \'1\' in the binary string.\n\nInitialize a flag variable, hasZero, to determine if \'0\' has been encountered in the string. This flag is used to decide whether an additional count needs to be added.\n\nIterate through the binary string character by character.\n\nWhen encountering \'0\', update endsWithZero by adding the current count of subsequences ending with \'1\'. Set hasZero to 1 to indicate the presence of \'0\'.\n\nWhen encountering \'1\', update endsWithOne by adding the counts of subsequences ending with \'0\' and \'1\' and incrementing by 1 to account for the current \'1\'.\n\nAfter processing the entire string, return the total number of unique good subsequences. If \'0\' is present in the string (hasZero is 1), add 1 to the result to account for the case where \'0\' itself is a good subsequence. \n\n\n\n# Complexity\n- Time complexity:\n O(n) - Linear time due to a single pass through the binary string. \n\n- Space complexity:\n O(1) - Constant space is used for variables; no additional data structures.\n\n# Code\n```\n/**\n * @param {string} binary\n * @return {number}\n */\n\nvar numberOfUniqueGoodSubsequences = function(binary) {\n // Define a constant MOD for later modulo operations\n const MOD = Math.pow(10, 9) + 7; // Set the constant MOD to 10^9 + 7\n \n // Initialize counts for subsequences \n let endsWithZero = 0;\n let endsWithOne = 0;\n \n // Initialize a variable to track if \'0\' has been seen in the string\n let hasZero = 0;\n \n // Iterate through the binary string character by character\n for (let i = 0; i < binary.length; i++) {\n // Check if the current character is \'0\'\n if (binary[i] === \'0\') {\n // Calculate the count of subsequences ending with \'0\'\n endsWithZero = (endsWithZero + endsWithOne) % MOD;\n \n // Set the \'hasZero\' flag to 1, indicating \'0\' has been seen\n hasZero = 1;\n } else {\n // Calculate the count of subsequences ending with \'1\'\n // These can be formed by adding \'1\' to both \'0\' and \'1\' subsequences\n endsWithOne = (endsWithZero + endsWithOne + 1) % MOD;\n }\n }\n\n // If \'0\' is present in the string, add 1 to the result; otherwise, use only endsWithOne\n return (endsWithOne + (hasZero + endsWithZero)) % MOD;\n};\n```
| 0 | 0 |
['String', 'Dynamic Programming', 'JavaScript']
| 0 |
number-of-unique-good-subsequences
|
Ruby solution with comments
|
ruby-solution-with-comments-by-ksodha93-y4hi
|
Approach\nThanks to Vishal\'s solution and original reference.\n\n# Complexity\n- Time complexity:\n Add your time complexity here, e.g. O(n) \nO(n) -> n = leng
|
ksodha93
|
NORMAL
|
2023-10-11T03:25:59.703423+00:00
|
2023-10-11T03:28:19.546216+00:00
| 0 | false |
# Approach\nThanks to [Vishal\'s solution](https://leetcode.com/problems/number-of-unique-good-subsequences/solutions/1749583/java-simple-solution-o-n-with-detailed-explanation/) and original [reference](https://www.codingninjas.com/studio/library/number-of-unique-good-subsequences).\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n) -> n = length of binary string\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n\n# Code\n```\n# @param {String} binary\n# @return {Integer}\ndef number_of_unique_good_subsequences(binary)\n ends_with_one = 0\n ends_with_zero = 0\n has_zero = 0 # to factor in single subsequence \'0\'\n mod = 10**9 + 7\n\n binary.each_char do |char|\n if char == \'1\'\n # + 1 indicates we are considering it as a subsequnce for future characters. For example, fututre appends will be like, 10, 11, 101, 1101(where the first one is the constant one (+1) and remaining characters we are adding which are valid)\n ends_with_one = (ends_with_one + ends_with_zero + 1) % mod\n else\n # no + 1 because we don\'t want to consider 0 as a separate subsequence. For example, any future appends to the substring will be 00, 01, 001, etc. (where the first zero is constant and remaining characters will be added but won\'t be valid based on given condition. Hence, no + 1)\n ends_with_zero = (ends_with_one + ends_with_zero) % mod\n has_zero = 1\n end\n end\n\n (ends_with_one + ends_with_zero + has_zero) % mod\nend\n```
| 0 | 0 |
['Ruby']
| 0 |
number-of-unique-good-subsequences
|
Python, runtime O(n), memory O(1)
|
python-runtime-on-memory-o1-by-tsai00150-c9n1
|
Got idea here: https://leetcode.com/problems/number-of-unique-good-subsequences/solutions/1431802/c-clean-dp-solution-with-explanation-time-o-n-space-o-1/\n\ncl
|
tsai00150
|
NORMAL
|
2023-10-03T02:45:34.882323+00:00
|
2023-10-03T02:45:34.882342+00:00
| 28 | false |
Got idea here: https://leetcode.com/problems/number-of-unique-good-subsequences/solutions/1431802/c-clean-dp-solution-with-explanation-time-o-n-space-o-1/\n```\nclass Solution:\n def numberOfUniqueGoodSubsequences(self, binary: str) -> int:\n end0 = end1 = hasZero = 0\n mod = 10**9+7\n for e in binary:\n if e == \'0\':\n hasZero = 1\n end0 = end0 + end1\n else:\n end1 = end0 + end1 + 1\n return (hasZero + end0 + end1)%mod\n```
| 0 | 0 |
['Python3']
| 0 |
number-of-unique-good-subsequences
|
Easy Solution
|
easy-solution-by-user20222-a8kp
|
\n\n# Approach\nFirst count without zero and then add 1 if zero is in string.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n
|
user20222
|
NORMAL
|
2023-08-17T04:18:45.794891+00:00
|
2023-08-17T04:18:45.794922+00:00
| 46 | false |
\n\n# Approach\nFirst count without zero and then add 1 if zero is in string.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\npublic:\n int mod = 1e9+7;\n int numberOfUniqueGoodSubsequences(string s) {\n int n = s.size();\n vector<int>dp(n,0);\n bool flag = 0;\n int sum=0;\n vector<int>hash(2,-1);\n for(int i=0;i<n;i++){\n dp[i] = sum+1;\n sum=(sum+dp[i])%mod;\n // cout<<sum<<endl;\n if(hash[s[i]-\'0\']!=-1)sum=((sum-dp[hash[s[i]-\'0\']])+mod)%mod;\n if(!flag&&s[i]==\'0\')sum--;\n if(s[i]==\'0\')flag=1;\n hash[s[i]-\'0\']=i;\n // cout<<sum<<endl;\n }\n // for(auto&it:dp)cout<<it<<\' \';cout<<endl;\n return sum+flag;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
number-of-unique-good-subsequences
|
Swift and Rust solutions
|
swift-and-rust-solutions-by-hsdsh-3xgy
|
\n# Code\nswift\n\nclass Solution {\n func numberOfUniqueGoodSubsequences(_ binary: String) -> Int {\n var e0 = 0\n var e1 = 0\n var h0
|
hsdsh
|
NORMAL
|
2023-07-08T12:19:30.504750+00:00
|
2023-07-08T12:19:30.504780+00:00
| 6 | false |
\n# Code\nswift\n```\nclass Solution {\n func numberOfUniqueGoodSubsequences(_ binary: String) -> Int {\n var e0 = 0\n var e1 = 0\n var h0 = 0\n for bi in Array(binary) {\n if bi == "1" {\n e1 = (e0 + e1 + 1) % 1_000_000_007\n } else {\n e0 = (e0 + e1) % 1_000_000_007\n h0 = 1\n }\n }\n return (e0 + e1 + h0) % 1_000_000_007\n }\n}\n\n```\nrust\n```\nimpl Solution {\n pub fn number_of_unique_good_subsequences(binary: String) -> i32 {\n let mut e0 = 0;\n let mut e1 = 0;\n let mut h0 = 0;\n for bi in &binary.chars().collect::<Vec<char>>() {\n if(bi==&\'1\'){\n e1 = (e0+e1+1)%1000000007;\n } else {\n e0 = (e0 + e1)%1000000007;\n h0 = 1;\n }\n }\n return (e0+e1+h0)%1000000007;\n }\n}\n```\n
| 0 | 0 |
['Swift', 'Rust']
| 0 |
number-of-unique-good-subsequences
|
Just a runnable solution
|
just-a-runnable-solution-by-ssrlive-xgx6
|
Code\n\nimpl Solution {\n pub fn number_of_unique_good_subsequences(binary: String) -> i32 {\n let mod_num = 1_000_000_007;\n let mut dp = vec!
|
ssrlive
|
NORMAL
|
2023-03-01T06:08:56.137622+00:00
|
2023-03-01T06:08:56.137667+00:00
| 15 | false |
# Code\n```\nimpl Solution {\n pub fn number_of_unique_good_subsequences(binary: String) -> i32 {\n let mod_num = 1_000_000_007;\n let mut dp = vec![0, 0];\n for c in binary.chars() {\n dp[c as usize - \'0\' as usize] = (dp[0] + dp[1] + c as usize - \'0\' as usize) % mod_num;\n }\n ((dp[0] + dp[1] + (binary.find(\'0\').is_some()) as usize) % mod_num) as _\n }\n}\n```
| 0 | 0 |
['Rust']
| 0 |
number-of-unique-good-subsequences
|
C++ || DP || Similar to Distinct Subsequences II
|
c-dp-similar-to-distinct-subsequences-ii-dd7e
|
\nclass Solution {\npublic:\n int numberOfUniqueGoodSubsequences(string binary) {\n vector<long long int> dp(binary.size(), 0);\n unordered_map
|
raghuvulli
|
NORMAL
|
2023-02-09T09:16:12.536405+00:00
|
2023-02-09T09:26:56.295636+00:00
| 71 | false |
```\nclass Solution {\npublic:\n int numberOfUniqueGoodSubsequences(string binary) {\n vector<long long int> dp(binary.size(), 0);\n unordered_map<char, int>last;\n last[\'0\'] = -1;\n last[\'1\'] = -1;\n int index = 0;\n int n = binary.size();\n int found = 0;\n int mod = 1e9 + 7;\n while(index < n && binary[index] == \'0\'){\n index++;\n found = 1;\n }\n if(index == n)\n return 1;\n dp[index] = 1;\n last[1] = index;\n for(int i = index+ 1; i <n ; i++){\n found = binary[i] == \'0\' ? 1 : found;\n dp[i] = (dp[i-1]*2) % mod;\n if(last[binary[i]] - 1 >= 0)\n dp[i] -= dp[last[binary[i]] - 1];\n dp[i] %= mod;\n last[binary[i]] = i;\n }\n // cout<<dp[n-1]<<endl;\n return (dp[n-1] < 0 ? dp[n-1] + mod : dp[n-1]) + (found == 1 ? 1 : 0);\n }\n};\n```
| 0 | 0 |
['Dynamic Programming', 'C']
| 1 |
number-of-unique-good-subsequences
|
The Easier Way | DP O(n) | Backward Iteration
|
the-easier-way-dp-on-backward-iteration-6p8wz
|
Intuition\nSuppose dp[i][bit] shows number of subsequences with all of it\'s bit indices greater or equal to i and starts with bit bit(0, 1). So, the recursive
|
itshesam
|
NORMAL
|
2023-01-28T20:52:44.032903+00:00
|
2023-01-28T20:56:57.720001+00:00
| 139 | false |
# Intuition\nSuppose ```dp[i][bit]``` shows number of subsequences with all of it\'s bit indices greater or equal to ```i``` and starts with bit ```bit```(0, 1). So, the recursive relation would be:\n```dp[i][bit] = dp[i + 1][0] + dp[i + 1][1] + 1```(+1 for single 1 or single zero). Therefore the optimized space solution would be like below:\n# Code\n```\nclass Solution:\n def numberOfUniqueGoodSubsequences(self, binary: str) -> int:\n dp = [0, 0]\n mod = int(1e9 + 7)\n for bit in [int(b) for b in binary][::-1]:\n dp[bit] = (1 + sum(dp)) % mod\n return (dp[1] + int(\'0\' in binary)) % mod\n\n```
| 0 | 0 |
['Python3']
| 1 |
number-of-unique-good-subsequences
|
Simple DP Solution || C++
|
simple-dp-solution-c-by-rkkumar421-pmhs
|
Approach\n Describe your approach to solving the problem. \nWe first have to remove leading zeros , and also do not have to include 0 in cnt0 \n# Complexity\n-
|
rkkumar421
|
NORMAL
|
2023-01-21T09:50:55.685345+00:00
|
2023-01-21T09:50:55.685391+00:00
| 145 | false |
# Approach\n<!-- Describe your approach to solving the problem. -->\nWe first have to remove leading zeros , and also do not have to include 0 in cnt0 \n# Complexity\n- Time complexity: O(N)\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 {\npublic:\n int numberOfUniqueGoodSubsequences(string b) {\n int lz = -1 , lo = -1; // last undex of zero and one\n int ind = 0, cnt0 = 0, M = 1e9 + 7;\n string tem = ""; // this will be new string after removing leading zeros\n if(b[0] == \'0\') cnt0 = 1;\n while(ind < b.length() && b[ind] == \'0\') ind++;\n while(ind < b.length()){ if(b[ind] ==\'0\') cnt0 = 1; tem += b[ind++]; }\n if(tem == "") return cnt0;\n vector<int> dp(tem.size()+1,0);\n dp[0] = 1; // 0 is for null in end we will remove it\n dp[1] = 2; // first char can have 2 sub sequence\n lo = 1; // always starting from 1\n for(int i = 1; i<tem.length();i++){\n if(tem[i] == \'0\'){ \n // if we get 0 then if this is first then only we cannot make 0 that\'s wy -1 \n // else removes previous zero sequences to remove duplicates\n if(lz == -1) dp[i+1] = (dp[i]*2ll - 1)%M;\n else dp[i+1] = (dp[i]*2ll - dp[lz-1] )%M;\n lz = i+1;\n }else{\n // similar as of zero \n if(lo == -1) dp[i+1] = (dp[i]*2ll)%M;\n else dp[i+1] = (dp[i]*2ll - dp[lo-1])%M;\n lo = i+1;\n }\n if(dp[i+1] < 0 ) dp[i+1] += M;\n }\n dp[tem.length()] -= (1-cnt0); // at last we will remove null and add 0 count\n if(dp[tem.length()] < 0 ) dp[tem.length()] += M;\n return dp[tem.length()]%M;\n }\n};\n```
| 0 | 0 |
['Dynamic Programming', 'C++']
| 0 |
number-of-unique-good-subsequences
|
c++ | dp
|
c-dp-by-shoaibtasrif326-97vq
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nDynamic Programming\n\n
|
shoaibtasrif326
|
NORMAL
|
2023-01-08T07:24:17.218499+00:00
|
2023-01-08T07:24:17.218544+00:00
| 60 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nDynamic Programming\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(n)\n# Code\n```\n#define ll long long\n\nclass Solution \n{\npublic:\n int numberOfUniqueGoodSubsequences(string binary) \n {\n int n=binary.size();\n ll mod=1e9+7;\n vector<ll> dp(n+9);\n int s=0, f=0;\n while( s<n && binary[s]==\'0\' ) s++, f=1;\n dp[s++]=1;\n vector<int> last(9, -1);\n\n for(int i=s ;i<=n;i++ )\n {\n int x=binary[i-1]-\'0\';\n if(x==0) f=1;\n dp[i]=( dp[i-1]*2 )%mod;\n if( last[x]>0 ) dp[i]=( dp[i]-dp[ last[x]-1 ] + mod ) % mod;\n else if( x==0 ) dp[i]=( dp[i]-dp[s-1]+mod ) % mod;\n last[x]=i;\n }\n\n if(!f)dp[n]=( dp[n]-1+mod )%mod;\n\n return dp[n];\n\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
number-of-unique-good-subsequences
|
C++ || Easy solution using DP faster than 95% 💥💥💥
|
c-easy-solution-using-dp-faster-than-95-tot1q
|
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
|
Shodydosh
|
NORMAL
|
2022-12-14T16:06:35.695277+00:00
|
2022-12-14T16:06:35.695340+00:00
| 99 | false |
# 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 {\npublic:\n int numberOfUniqueGoodSubsequences(string binary) {\n const int mod = 1e9+7;\n long long dp[2][2] = {};\n // dp[i][j] stands for number of good subsequences \n // start with i and end with j \n\n for(char a : binary){\n if(a == \'0\'){\n // to check if there are any \'0\' in the string\n dp[0][0] = 1;\n\n // good subsequences end with 0\n dp[1][0] = (dp[1][0] + dp[1][1]) % mod;\n }\n else {\n // good subsequences end with 1\n dp[1][1] = (dp[1][0] + dp[1][1] + 1) % mod;\n // +1 because there will be "1" and then add 1 to the end it become "11"\n // so adding back "1"\n }\n }\n\n return (dp[1][1] + dp[0][0] + dp[1][0]) % mod;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
number-of-unique-good-subsequences
|
Python solution
|
python-solution-by-vincent_great-zeh3
|
\ndef numberOfUniqueGoodSubsequences(self, s: str) -> int:\n\td, mod = [0, 0], 10**9+7\n\tfor n in s:\n\t\td[int(n)] = sum(d)+(n==\'1\')\n\treturn (sum(d) + (\'
|
vincent_great
|
NORMAL
|
2022-12-01T08:44:20.984590+00:00
|
2022-12-01T08:44:20.984629+00:00
| 30 | false |
```\ndef numberOfUniqueGoodSubsequences(self, s: str) -> int:\n\td, mod = [0, 0], 10**9+7\n\tfor n in s:\n\t\td[int(n)] = sum(d)+(n==\'1\')\n\treturn (sum(d) + (\'0\'in s))%mod\n```
| 0 | 0 |
[]
| 0 |
number-of-unique-good-subsequences
|
C++ || DP Solution
|
c-dp-solution-by-rohitraj13may1998-zvq9
|
\nclass Solution {\npublic:\n int numberOfUniqueGoodSubsequences(string binary) {\n bool hasZero = false;\n int endWithZeroes=0,endWithOnes=0,mo
|
rohitraj13may1998
|
NORMAL
|
2022-11-21T16:24:32.447134+00:00
|
2022-11-21T16:24:32.447176+00:00
| 35 | false |
```\nclass Solution {\npublic:\n int numberOfUniqueGoodSubsequences(string binary) {\n bool hasZero = false;\n int endWithZeroes=0,endWithOnes=0,mod=1e9+7;\n \n for(auto b:binary){\n if(b==\'1\'){\n endWithOnes = (endWithOnes + endWithZeroes + 1)%mod;\n }else{\n hasZero=true;\n endWithZeroes = (endWithOnes + endWithZeroes)%mod;\n }\n }\n \n return (endWithOnes + endWithZeroes + hasZero)%mod;\n }\n};\n```
| 0 | 0 |
[]
| 0 |
number-of-unique-good-subsequences
|
Scala DP end with 0 and end with 1
|
scala-dp-end-with-0-and-end-with-1-by-ir-cu6a
|
\nobject Solution {\n // Memory Limit Exceeded on "111001101100000001001110110101110001100"\n def numberOfUniqueGoodSubsequencesBad0(binary: String): Int
|
ironmask
|
NORMAL
|
2022-10-17T05:27:23.626464+00:00
|
2022-10-17T05:29:23.869296+00:00
| 28 | false |
```\nobject Solution {\n // Memory Limit Exceeded on "111001101100000001001110110101110001100"\n def numberOfUniqueGoodSubsequencesBad0(binary: String): Int = {\n var seen=scala.collection.mutable.Set[Int]()\n var num=0\n var mod=math.pow(10,9)+7\n def ps(i:Int,num:Int,firstChar:Char=0) : Unit = { //math.pow(2,31)-1-1e9>=0\n if (i==binary.size) {if (firstChar!=0) seen += num}\n else {\n if (firstChar!=\'0\') ps(i+1,num<<1|binary(i)-\'0\',firstChar.max(binary(i)))\n ps(i+1,num,firstChar)\n }\n }\n ps(0,0)\n (seen.size)%mod.toInt\n }\n\t\n\t//DP iterative, break down by ending with 0 or 1, \n def numberOfUniqueGoodSubsequences(binary: String): Int = {\n // a power set is the accumulated/running set of all previous sets plus appended current element to previous set (without and without current elemement)\n var zeroes,ones,total=0\n val mod=(1e9+7).toInt\n for (c <- binary) {\n if (c==\'1\') ones=(ones+zeroes+1)%mod\n else zeroes= (zeroes+ones)%mod\n }\n (ones+zeroes+(if (binary.contains(\'0\')) 1 else 0))%mod\n }\n}\n```
| 0 | 0 |
[]
| 0 |
number-of-unique-good-subsequences
|
C++ | O(N) | DP | Similar to Distinct Subsequences II
|
c-on-dp-similar-to-distinct-subsequences-iyja
|
Please do upvote if found useful!!\n\nclass Solution {\npublic:\n const int M = 1e9 + 7;\n int numberOfUniqueGoodSubsequences(string s) {\n int n=s
|
Chakit_Bhandari
|
NORMAL
|
2022-10-15T18:46:03.488452+00:00
|
2022-10-15T18:47:09.890320+00:00
| 61 | false |
Please do upvote if found useful!!\n```\nclass Solution {\npublic:\n const int M = 1e9 + 7;\n int numberOfUniqueGoodSubsequences(string s) {\n int n=s.size();\n vector<int>t(2,-1);\n int ans = 0;\n for(int e=0;e<n;++e){\n if(t[s[e] - \'0\'] == -1){\n t[s[e]-\'0\'] = ans;\n ans = ((long long)2*ans + 1)%M;\n }\n else{\n int prev = ans;\n ans = ((long long)2*ans - t[s[e]-\'0\'] + M)%M;\n t[s[e] - \'0\'] = prev;\n }\n } \n \n int final_ = ans;\n ans = 0;\n int val = 0;\n t = {-1,-1};\n for(int e=n-1;e>=0;--e){\n if(t[s[e] - \'0\'] == -1){\n t[s[e]-\'0\'] = ans;\n val = ((long long)val + (s[e] == \'0\')*ans)%M;\n ans = ((long long)2*ans + 1)%M;\n }else{\n int prev = ans;\n val = ((long long)val + (s[e] == \'0\')*(ans - t[s[e]-\'0\'] + M))%M;\n ans = ((long long)ans*2 - t[s[e]-\'0\'] + M)%M;\n t[s[e]-\'0\'] = prev;\n }\n }\n \n final_ = ((long long)final_ - val + M)%M;\n return final_;\n \n /*\n The total no of unique good subsequences is the sum of the total distinct sequences - total_no of distinct \n\t\tsequences starting with 0. So to calculate the no of distinct sequences starting with 0, just traverse from the\n\t\tend and find the count of sequences ending at 0. (ending at 0 because we have traversed from the back of the\n\t\tarray so ending from back is same as calculating starting from front.)\n */\n } \n};\n```
| 0 | 0 |
['Dynamic Programming']
| 0 |
number-of-unique-good-subsequences
|
scala solution
|
scala-solution-by-lyk4411-2chr
|
\n def numberOfUniqueGoodSubsequences(binary: String): Int = {\n val mod = 1000000007\n val res = binary.foldLeft((0, 0, 0))((ans, cur)=>{\n if(cur
|
lyk4411
|
NORMAL
|
2022-10-04T12:44:38.460932+00:00
|
2022-10-04T12:44:38.460974+00:00
| 13 | false |
```\n def numberOfUniqueGoodSubsequences(binary: String): Int = {\n val mod = 1000000007\n val res = binary.foldLeft((0, 0, 0))((ans, cur)=>{\n if(cur == \'1\') (ans._1, (ans._2 + ans._1 + 1) % mod, ans._3)\n else ((ans._1 + ans._2) % mod, ans._2, 1)\n })\n (res._2 + res._1 + res._3) % mod\n }\n```
| 0 | 0 |
['Scala']
| 0 |
number-of-unique-good-subsequences
|
Python Simple DP Solution
|
python-simple-dp-solution-by-hemantdhami-w9ls
|
We start with "0" then stop, only one subsequence. Otherwise, on each position, we have two choices, either take it or not take it\n\nBut how to avoid duplicate
|
hemantdhamija
|
NORMAL
|
2022-09-18T07:48:13.066452+00:00
|
2022-09-18T07:49:22.257850+00:00
| 119 | false |
We start with "0" then stop, only one subsequence. Otherwise, on each position, we have two choices, either take it or not take it\n\nBut how to avoid duplicates ?\n\ndp[i][j]= no of distinct subsequences starting with (i=0/1) and ends with (j=0/1) or look likes [i...j]\n\nans= dp[0][0]+dp[0][1]+dp[1][0]+dp[1][1]\n\nif s[i]==\'0\', we stick this \'0\' to all subsequences of type [1....0] and [1...1]. So, dp[1][0] increases to dp[1][0]+dp[1][1]. Also we can make one subsequence of type "0" (dp[0][0]). So we make dp[0][0]=1\n\n(NOTE subsequence of type [0...1] is not valid)\n\nif s[i]==\'1\', we stick this \'1\' to all subsequences of type [1...0] and [1....1], also, we can get one new subsequence that is "1". So dp[1][1] increases to dp[1][0]+dp[1][1]+1\n\nans= dp[0][0]+dp[0][1]+dp[1][0]+dp[1][1]\n\n```\nclass Solution:\n def numberOfUniqueGoodSubsequences(self, binary: str) -> int:\n dp, sz = [[0, 0], [0, 0]], len(binary)\n for bit in binary:\n if bit == \'0\':\n dp[0][0] = 1\n dp[1][0] += dp[1][1]\n else:\n dp[1][1] += (dp[1][0] + 1)\n return (dp[0][0] + dp[0][1] + dp[1][0] + dp[1][1]) % 1000000007\n```
| 0 | 0 |
['Dynamic Programming', 'Python']
| 0 |
number-of-unique-good-subsequences
|
JS Solution
|
js-solution-by-creativerahuly-pdmz
|
\nconst MOD = 1000000007;\n\nvar numberOfUniqueGoodSubsequences = function(binary) {\n let endsZero = 0;\n let endsOne = 0;\n let hasZero = 0;\n for
|
creativerahuly
|
NORMAL
|
2022-09-06T05:51:24.063436+00:00
|
2022-09-06T05:51:24.063480+00:00
| 45 | false |
```\nconst MOD = 1000000007;\n\nvar numberOfUniqueGoodSubsequences = function(binary) {\n let endsZero = 0;\n let endsOne = 0;\n let hasZero = 0;\n for (let i = 0; i < binary.length; i++) {\n if (binary[i] === \'1\') {\n endsOne = (endsZero + endsOne + 1) % MOD;\n } else {\n endsZero = (endsZero + endsOne) % MOD;\n hasZero = 1;\n }\n }\n return (endsZero + endsOne + hasZero) % MOD;\n};\n```
| 0 | 0 |
['JavaScript']
| 0 |
number-of-unique-good-subsequences
|
[C++] | DP - Bottom UP | O(N) time, O(1) space
|
c-dp-bottom-up-on-time-o1-space-by-crims-e5ph
|
\ntypedef long long ll;\nclass Solution {\n const int mod = 1e9+7;\npublic:\n int numberOfUniqueGoodSubsequences(string s) {\n int len = s.size();\
|
crimsonX
|
NORMAL
|
2022-07-16T15:05:49.329454+00:00
|
2022-07-16T15:07:25.736704+00:00
| 254 | false |
```\ntypedef long long ll;\nclass Solution {\n const int mod = 1e9+7;\npublic:\n int numberOfUniqueGoodSubsequences(string s) {\n int len = s.size();\n auto first=s[0]-\'0\';\n \n ll zero=0,one=first;\n bool z=!first;\n ll ans=first;\n for(int x=1;x<len;x++){\n auto i=s[x]-\'0\';\n ll res=ans;\n if(i==0){\n z=true;\n res=(res-zero+mod)%mod;\n ans=(ans+res)%mod;\n zero=(res+zero)%mod;\n }\n else{\n res++;\n res=(res-one+mod)%mod;\n ans=(ans+res)%mod;\n one=(res+one)%mod;\n } \n }\n return (ans+(ll)z)%mod;\n }\n};\n```
| 0 | 0 |
['Dynamic Programming', 'C', 'C++']
| 0 |
number-of-unique-good-subsequences
|
C++ | Dynamic Programming - Bottom UP | TIME - O(N) AND SPACE -O(N)
|
c-dynamic-programming-bottom-up-time-on-tu87v
|
Similar to Distinct Subsequences 2\n\nclass Solution {\npublic:\n int numberOfUniqueGoodSubsequences(string binary) {\n int n=binary.size();\n
|
niks07
|
NORMAL
|
2022-07-15T14:34:55.420089+00:00
|
2022-07-15T14:34:55.420120+00:00
| 102 | false |
**Similar to Distinct Subsequences 2**\n```\nclass Solution {\npublic:\n int numberOfUniqueGoodSubsequences(string binary) {\n int n=binary.size();\n int mod=1e9+7;\n vector<long> dp(n,0);\n int a=-1, b=-1;\n bool flag=false;\n \n if(binary[0]==\'0\'){\n a=0;\n }else{\n b=0;\n dp[0]=1;\n }\n \n for(int i=1; i<n; i++){\n char ch=binary[i];\n if(ch==\'0\'){\n if(a==-1){\n dp[i]=2*dp[i-1]%mod;\n }else{\n if(a!=0)\n dp[i]=(2*dp[i-1]%mod-dp[a-1]+mod)%mod;\n else\n dp[i]=2*dp[i-1]%mod;\n }\n a=i;\n }else{\n if(b==-1)\n dp[i]=1+2*dp[i-1]%mod;\n else{\n if(b!=0)\n dp[i]=(2*dp[i-1]%mod-dp[b-1]+mod)%mod;\n else\n dp[i]=2*dp[i-1]%mod;\n }\n\n b=i;\n }\n }\n \n \n \n return a>=0 ? dp[n-1]+1 : dp[n-1];\n }\n};\n```
| 0 | 0 |
['Dynamic Programming', 'C']
| 0 |
number-of-unique-good-subsequences
|
C++ | DP
|
c-dp-by-__priyanshu-zgcz
|
class Solution {\nint M = 1e9 + 7;\npublic:\n int numberOfUniqueGoodSubsequences(string binary) {\n \n int n = binary.size();\n vector d
|
__priyanshu__
|
NORMAL
|
2022-07-03T18:50:41.212187+00:00
|
2022-07-03T18:50:51.466495+00:00
| 124 | false |
class Solution {\n` int M = 1e9 + 7;`\npublic:\n int numberOfUniqueGoodSubsequences(string binary) {\n \n int n = binary.size();\n vector<long long> dp(n + 1, 0);\n int prev_zero = 0, prev_one = 0;\n \n int i = 1;\n for(; i <= n && binary[i - 1] == \'0\'; i++);\n \n if(i > n)\n return 1;\n \n dp[i] = 1;\n prev_one = i - 1;\n \n bool zero_flag = i > 1;\n for(i++; i <= n; i++)\n {\n dp[i] = 2 * dp[i - 1];\n \n if(binary[i - 1] - \'0\')\n dp[i] -= dp[prev_one], prev_one = i - 1;\n else\n dp[i] -= dp[prev_zero], prev_zero = i - 1, zero_flag = true;\n \n if(dp[i] < 0)\n dp[i] += M;\n \n dp[i] %= M;\n }\n \n return (dp[n] + zero_flag) % M;\n }\n};
| 0 | 0 |
['Dynamic Programming', 'C']
| 0 |
number-of-unique-good-subsequences
|
C++ O(n) time O(1) space solution
|
c-on-time-o1-space-solution-by-nam__ra-mdbp
|
\nclass Solution {\npublic:\n int numberOfUniqueGoodSubsequences(string s) {\n unsigned long long prevo=0;\n unsigned long long prevz=0;\n
|
Nam__ra
|
NORMAL
|
2022-05-07T11:35:48.867329+00:00
|
2022-05-07T11:35:48.867368+00:00
| 180 | false |
```\nclass Solution {\npublic:\n int numberOfUniqueGoodSubsequences(string s) {\n unsigned long long prevo=0;\n unsigned long long prevz=0;\n unsigned long long ans=0;\n int ff=-1;\n int f=0;\n int mod=1000000007;\n for(int i=0;i<s.size();i++)\n \n {\n if(s[i]==\'0\')\n {\n int x=ans;\n ans+=mod+ans-prevz ;\n prevz=x;\n f=1;\n ans=ans%mod;\n }\n else\n { \n int x=ans;\n if(ff==-1) {ans=1;ff=1;}\n else\n ans+=mod+ans-prevo;\n ans=ans%mod;\n prevo=x;\n }\n }\n return (ans+ f)%mod;\n }\n};\n```
| 0 | 0 |
[]
| 0 |
number-of-unique-good-subsequences
|
C++ DP Solution with O(n) time and O(1) space
|
c-dp-solution-with-on-time-and-o1-space-dgag5
|
My thought process:\n1. The statement of "the result might too big and use the modulo 1e9 + 7" confirms that it must be a DP problem.\n2. I then tried to first
|
clark3
|
NORMAL
|
2022-04-16T06:41:12.586836+00:00
|
2022-04-16T06:41:12.586864+00:00
| 209 | false |
My thought process:\n1. The statement of "the result might too big and use the modulo 1e9 + 7" confirms that it must be a DP problem.\n2. I then tried to firstly build the base cases of and define the state transitions\n\n```\nclass Solution {\npublic:\n int numberOfUniqueGoodSubsequences(string binary) {\n const int MOD = 1e9 + 7;\n int dp_zero = 0, dp_one = 0;\n\t\t// f(i, 0) = the number of unique subsequences starting with 0 (note that these subsequences are not good since they all have the staring zeros)\n\t\t// f(i, 1) = the number of good unique subsequences starting with 1\n\t\t// Once we have the base cases the new states can be calculated as in the code below\t\t\n \n dp_zero = binary.back() == \'0\' ? 1 : 0; \n dp_one = binary.back() == \'1\' ? 1 : 0;\n bool zero = binary.back() == \'0\';\n for (int i = binary.size() - 2; i >= 0; --i) {\n if (binary[i] == \'0\') {\n\t\t\t\t// With the new 0, all the f(i + 1, 1) can be used to derive a new subsequence. f(i + 1, 0) can also be used to derive a longer subsequence therefore add 1 here.\n\t\t\t\t\n dp_zero = dp_zero + 1 + dp_one;\n }\n else { \n dp_one = dp_one + 1 + dp_zero;\n }\n\t\t\t// Handle the single digit sequence with 0 only\n zero |= binary[i] == \'0\';\n dp_zero %= MOD;\n dp_one %= MOD; \n }\n return (dp_one + zero) % MOD;\n }\n};\n```
| 0 | 0 |
['Dynamic Programming']
| 0 |
number-of-unique-good-subsequences
|
C++ DP solution
|
c-dp-solution-by-navneetkchy-i6cr
|
\nclass Solution {\npublic:\n const int mod = 1e9 + 7;\n int numberOfUniqueGoodSubsequences(string binary) {\n int n = binary.size();\n vect
|
navneetkchy
|
NORMAL
|
2022-04-15T03:00:42.604425+00:00
|
2022-04-15T03:00:42.604451+00:00
| 135 | false |
```\nclass Solution {\npublic:\n const int mod = 1e9 + 7;\n int numberOfUniqueGoodSubsequences(string binary) {\n int n = binary.size();\n vector<int> dp(n + 1);\n dp[n] = 1;\n int one = -1;\n int zero = -1;\n for (int i = n - 1; i >= 0; i--) {\n if (binary[i] == \'1\') {\n dp[i] = (2 * dp[i + 1]) % mod;\n if (one != -1) {\n dp[i] -= dp[one + 1];\n if (dp[i] < 0) {\n dp[i] += mod;\n }\n }\n one = i;\n }\n else {\n dp[i] = (2 * dp[i + 1]) % mod;\n if (zero != -1) {\n dp[i] -= dp[zero + 1];\n if (dp[i] < 0) {\n dp[i] += mod;\n }\n }\n zero = i;\n }\n }\n int sol = dp[0] - 1;\n if (sol < 0) {\n sol += mod;\n }\n for (int i = 0; i < n; i++) {\n if (binary[i] == \'0\') {\n sol -= dp[i + 1];\n if (sol < 0) {\n sol += mod;\n }\n sol = (sol + 1) % mod;\n break;\n }\n }\n return sol;\n }\n};\n```
| 0 | 0 |
[]
| 0 |
number-of-unique-good-subsequences
|
C++ | O(n) time O(1) space
|
c-on-time-o1-space-by-sonusharmahbllhb-wfs6
|
\nclass Solution {\npublic:\n long md=1e9+7;\n int numberOfUniqueGoodSubsequences(string binary) {\n long zo=0,o=0,z=0;\n \n long ans
|
sonusharmahbllhb
|
NORMAL
|
2022-03-22T14:41:32.176885+00:00
|
2022-03-22T14:41:32.176926+00:00
| 211 | false |
```\nclass Solution {\npublic:\n long md=1e9+7;\n int numberOfUniqueGoodSubsequences(string binary) {\n long zo=0,o=0,z=0;\n \n long ans=0;\n \n for(auto &ch:binary) if(ch==\'0\') ans=1;\n \n int l=0;\n \n while(l<binary.length() and binary[l]==\'0\') l++;\n \n if(l==binary.length()) return ans;\n \n zo=1;\n \n l++;\n \n while(l<binary.length()){\n if(binary[l]==\'0\'){\n ans+=z;\n o+=zo;\n zo+=z;\n z=0;\n \n }\n else{\n ans+=o;\n z+=zo;\n zo+=o;\n o=0;\n \n }\n l++;\n ans=ans%md;\n zo=zo%md; \n }\n ans=(ans+zo+z+o)%md;\n return ans;\n \n }\n};\n```
| 0 | 0 |
['C', 'C++']
| 0 |
number-of-unique-good-subsequences
|
DP BOTTOM UP O(N) , JAVA, EASY
|
dp-bottom-up-on-java-easy-by-goginenikir-g1gy
|
\nclass Solution {\n public int numberOfUniqueGoodSubsequences(String s) {\n int n=s.length();\n int mod=(int)1e9+7;\n int dp[]=new int[
|
goginenikiran11
|
NORMAL
|
2022-03-12T06:08:48.167068+00:00
|
2022-03-12T06:08:48.167119+00:00
| 171 | false |
```\nclass Solution {\n public int numberOfUniqueGoodSubsequences(String s) {\n int n=s.length();\n int mod=(int)1e9+7;\n int dp[]=new int[n+1];\n int x=-1,y=-1,flag=0;\n if(s.charAt(0)==\'1\') {\n y=0;\n dp[1]=1;\n }\n else\n flag=1;\n if(n==1) return 1;\n for(int i=2;i<=n;i++)\n {\n char ch=s.charAt(i-1);\n if(ch==\'0\' && y==-1)\n continue;\n dp[i]=(2*dp[i-1])%mod;\n if(ch==\'1\')\n {\n if(y==-1)\n dp[i]=(dp[i]+1)%mod;\n else\n dp[i]=(dp[i]-dp[y]+mod)%mod;\n y=i-1;\n } \n else\n {\n flag=1;\n if(x!=-1)\n dp[i]=(dp[i]-dp[x]+mod)%mod;\n x=i-1;\n }\n \n }\n return flag==1?dp[n]+1:dp[n];\n }\n}\n```
| 0 | 0 |
[]
| 0 |
number-of-unique-good-subsequences
|
Python Simple and elegant 2 pointer DP
|
python-simple-and-elegant-2-pointer-dp-b-ixul
|
Assume leading zero is not allowed (including single 0 case). If we find single 0, add it back.\n\nclass Solution:\n def numberOfUniqueGoodSubsequences(self,
|
PSG_LGD_Ana
|
NORMAL
|
2022-02-09T04:22:53.398280+00:00
|
2022-02-09T04:24:16.858478+00:00
| 132 | false |
Assume leading zero is not allowed (including single 0 case). If we find single 0, add it back.\n```\nclass Solution:\n def numberOfUniqueGoodSubsequences(self, binary: str) -> int:\n last_one=0\n last_zero=0\n has_zero=0\n MOD=10**9+7\n for i in range(len(binary)):\n if binary[i]=="0":\n has_zero=1\n break\n for i in range(len(binary)):\n if binary[i]=="1":\n ## leading 1 is allowed\n ## 10,11 (next digit is 1)-> 101, 111, 1\n ## 101,111,1-> 1011, 1111, 11\n last_one+=last_zero+1\n else:\n ## leading 0 not allowed\n ## 10,11-> 100, 110\n last_zero+=last_one\n return (last_one+last_zero+has_zero)%MOD\n```
| 0 | 0 |
['Two Pointers', 'Dynamic Programming']
| 0 |
number-of-unique-good-subsequences
|
Python Soln - DP O(n)
|
python-soln-dp-on-by-oluomo_lade-gkk3
|
\tclass Solution:\n\t\tdef numberOfUniqueGoodSubsequences(self, binary: str) -> int:\n\t\t\tn = len(binary)\n\t\t\ts = 0\n\t\t\tmod = (109)+7\n\t\t\t#Time O(n),
|
oluomo_lade
|
NORMAL
|
2022-02-04T15:07:17.539027+00:00
|
2022-02-04T15:07:17.539062+00:00
| 113 | false |
\tclass Solution:\n\t\tdef numberOfUniqueGoodSubsequences(self, binary: str) -> int:\n\t\t\tn = len(binary)\n\t\t\ts = 0\n\t\t\tmod = (10**9)+7\n\t\t\t#Time O(n), Space O(n)\n\t\t\t# increase s while there are leading zeros\n\t\t\twhile s < n and binary[s] == \'0\':\n\t\t\t\ts += 1\n\n\t\t\tif s == n:\n\t\t\t\treturn 1\n\n\t\t\tdp = [0]*n\n\t\t\tdp[s] = 1\n\t\t\tlastZero = lastOne = 0\n\n\t\t\tfor i in range(s+1, n):\n\t\t\t\tj = lastZero if binary[i] == \'0\' else lastOne\n\t\t\t\tdup = dp[j-1] if j > 0 else 0\n\n\t\t\t\tdp[i] = 2*dp[i-1] - dup #num of unique subseq\n\n\t\t\t\tif binary[i] == \'0\':\n\t\t\t\t\tlastZero = i\n\t\t\t\telse:\n\t\t\t\t\tlastOne = i\n\n\t\t\tlastZero = 0 \n\t\t\t#add one zero from the leading zeros as a unique subseq\n\t\t\tif \'0\' in binary:\n\t\t\t\tlastZero += 1\n\n\t\t\treturn (dp[-1] + lastZero) % mod
| 0 | 0 |
[]
| 0 |
number-of-unique-good-subsequences
|
Python DP without split - O(N) O(1)
|
python-dp-without-split-on-o1-by-bz2342-yjho
|
\nclass Solution:\n def numberOfUniqueGoodSubsequences(self, binary: str) -> int:\n \'\'\'\n DP: \n dp[i] := number of unique good subse
|
bz2342
|
NORMAL
|
2022-01-09T21:28:27.200621+00:00
|
2022-01-09T21:28:27.200662+00:00
| 139 | false |
```\nclass Solution:\n def numberOfUniqueGoodSubsequences(self, binary: str) -> int:\n \'\'\'\n DP: \n dp[i] := number of unique good subseq of binary[:i+1] \n including empty one\n 1) dp[i+1] = dp[i] * 2\n 2) however, we need to remove duplicates caused by previous\n same char, let the corresponding index be j. then we need\n to remove dp[j-1] (similar to 940. Distinct Subsequences II)\n 3) also, we need to remove 0_ if we have 0 previously, this\n this tracked by has0\n 4) however, there could be 1 overlap in 2) and 3) if we has 0 in\n both s[:j] and s[:i] as \'0_\' is removed twice, as we need to \n add 1 if prev_h0 == True\n \'\'\'\n dp = 1 # empty subseq\n prev_cnt = {"1": (0, False), "0": (0, False)}\n has0 = False\n for i, char in enumerate(binary):\n prev_c, prev_h0 = prev_cnt[char]\n prev_cnt[char], dp = (dp, has0), dp * 2 - prev_c - has0 + prev_h0 \n if char == \'0\':\n has0 = True\n return (dp - 1) % 1000000007\n```
| 0 | 0 |
[]
| 0 |
number-of-unique-good-subsequences
|
python 3
|
python-3-by-g0urav-4duy
|
\nclass Solution:\n def numberOfUniqueGoodSubsequences(self, binary: str) -> int:\n j=0\n sub=False\n count=0\n while j<len(binar
|
g0urav
|
NORMAL
|
2021-11-06T18:38:07.431738+00:00
|
2021-11-06T18:38:07.431768+00:00
| 108 | false |
```\nclass Solution:\n def numberOfUniqueGoodSubsequences(self, binary: str) -> int:\n j=0\n sub=False\n count=0\n while j<len(binary):\n if binary[j]==\'1\':\n count=1\n prev1=0\n prev2=0\n break\n if binary[j]==\'0\':\n sub=True\n j+=1\n for i in range(j+1,len(binary)):\n if binary[i]==\'0\':\n mid=count\n count+=(count-prev1)\n prev1=mid\n sub=True\n else:\n mid=count\n count+=(count-prev2)\n prev2=mid\n if sub==True:\n count+=1\n return count%(10**9+7)\n```
| 0 | 0 |
[]
| 0 |
number-of-unique-good-subsequences
|
Simple O(N) DP
|
simple-on-dp-by-codeantik_099-52nw
|
\nclass Solution {\npublic:\n const int mod = 1e9 + 7;\n \n int numberOfUniqueGoodSubsequences(string s) {\n int n = s.size();\n vector<i
|
codeantik_099
|
NORMAL
|
2021-10-21T16:26:57.814886+00:00
|
2021-10-21T16:26:57.814918+00:00
| 266 | false |
```\nclass Solution {\npublic:\n const int mod = 1e9 + 7;\n \n int numberOfUniqueGoodSubsequences(string s) {\n int n = s.size();\n vector<int> dp(n, 0);\n int zeroPos, onePos, start;\n bool zeroPresent = false;\n start = zeroPos = onePos = 0;\n \n while(start < n && s[start] == \'0\') start++;\n \n if(start == n) return 1;\n \n dp[start] = 1;\n \n for(int i = start + 1; i < n; i++) {\n int j = (s[i] == \'0\' ? zeroPos : onePos);\n dp[i] = (dp[i - 1] * 2 % mod - (j > 0 ? dp[j - 1] : 0) + mod) % mod;\n if(s[i] == \'0\') zeroPos = i;\n else onePos = i;\n }\n \n zeroPresent |= count(begin(s), end(s), \'0\');\n return dp[n - 1] + zeroPresent;\n }\n};\n```
| 0 | 0 |
[]
| 0 |
number-of-unique-good-subsequences
|
easy python3
|
easy-python3-by-alankritrastogi-anhc
|
\nclass Solution:\n def numberOfUniqueGoodSubsequences(self, binary: str) -> int:\n d=defaultdict(int)\n i=0;mod=(10**9)+7\n su=0;j=0\n
|
alankritrastogi
|
NORMAL
|
2021-10-20T06:55:22.915924+00:00
|
2021-10-20T06:55:22.915963+00:00
| 94 | false |
```\nclass Solution:\n def numberOfUniqueGoodSubsequences(self, binary: str) -> int:\n d=defaultdict(int)\n i=0;mod=(10**9)+7\n su=0;j=0\n print(len(binary))\n while i<len(binary) and binary[i]!="1":i+=1;j=1\n if i<len(binary):\n su=1;i+=1\n while i<len (binary):\n if binary[i]=="1":\n tmp=su*2\n full=tmp-d[1]\n d[1]+=full-su\n su=full\n else:\n tmp=su*2\n full=tmp-d[0]\n d[0]+=full-su\n su=full\n i+=1\n return (su+1)%mod if j==1 or d[0]>0 else su%mod \n \n \n \n```
| 0 | 0 |
[]
| 0 |
number-of-unique-good-subsequences
|
DP approach and similar question
|
dp-approach-and-similar-question-by-raja-tqay
|
I know there are other solutions that involve O(1) space and O(n) time. I anyways will post my DP solution. The idea is inspired from https://leetcode.com/probl
|
rajat8020
|
NORMAL
|
2021-09-14T21:52:12.058890+00:00
|
2021-09-14T21:52:12.058933+00:00
| 315 | false |
I know there are other solutions that involve O(1) space and O(n) time. I anyways will post my DP solution. The idea is inspired from https://leetcode.com/problems/number-of-unique-good-subsequences/\ncount distinct subsequences problem on leetcode itself. Here is well commented code:\n\n```\nclass Solution {\npublic:\n int mod = 1e9 + 7;\n int numberOfUniqueGoodSubsequences(string str) {\n int n = str.size();\n // dp0[i] represents number of subsequences starting with 0 from index i\n // dp1[i] represents number of subsequences starting with 1 from index i\n vector<long> dp0(n + 1), dp1(n + 1);\n int i, c = 0;\n // M stores the last occurence of character (in our case it can be either 0 or 1)\n map<char, int> M;\n \n // rest of the transition is same as problem: count number of distinct subsequences.\n for(i = n - 1; i >= 0; --i) {\n if(str[i] == \'0\') {\n c = 1;\n dp0[i] = dp1[i + 1] + 2 * dp0[i + 1] + 1;\n if(M.count(str[i])) {\n dp0[i] -= (dp0[M[str[i]] + 1] + dp1[M[str[i]] + 1] + 1);\n }\n dp1[i] = dp1[i + 1];\n dp0[i] += mod;\n dp0[i] %= mod;\n } else {\n dp1[i] = 2 * dp1[i + 1] + dp0[i + 1] + 1;\n if(M.count(str[i])) {\n dp1[i] -= (dp0[M[str[i]] + 1] + dp1[M[str[i]] + 1] + 1);\n }\n dp0[i] = dp0[i + 1];\n dp1[i] += mod;\n dp1[i] %= mod;\n }\n M[str[i]] = i;\n }\n for(int i = 0; i < n; ++i) {\n if(str[i] == \'1\') {\n return dp1[i] + c;\n }\n }\n return c;\n \n }\n};\n```
| 0 | 0 |
[]
| 0 |
number-of-unique-good-subsequences
|
Python DP From Naive to Optimized
|
python-dp-from-naive-to-optimized-by-dav-qn1w
|
Start off with the most naive approach(TLE)\n\nclass Solution:\n def numberOfUniqueGoodSubsequences(self, binary: str) -> int:\n # dp[i]: good subsequ
|
davidp918
|
NORMAL
|
2021-09-04T09:14:00.835272+00:00
|
2021-09-04T09:15:01.345232+00:00
| 231 | false |
Start off with the most naive approach(TLE)\n```\nclass Solution:\n def numberOfUniqueGoodSubsequences(self, binary: str) -> int:\n # dp[i]: good subsequences of binary[:i+1]\n\t\t\n n = len(binary)\n dp = [set(binary[i]) for i in range(n)]\n \n for i in range(n):\n cur = binary[i]\n for j in range(i):\n for good in dp[j]:\n if good[0] != \'0\':\n dp[i].add(good + cur)\n \n return len(set.union(*dp))\n```\nOptimize dp from O(n^2) to O(n) since it\'s the same as adding new subsequences to the same set(TLE)\n```\nclass Solution:\n def numberOfUniqueGoodSubsequences(self, binary: str) -> int:\n n = len(binary)\n dp = set(binary[0])\n\n for i in range(1, n):\n for good in set(dp):\n if good[0] != \'0\':\n dp.add(good + binary[i])\n dp.add(binary[i])\n \n return len(dp)\n```\nDP over number instead of strings\n```\nclass Solution:\n def numberOfUniqueGoodSubsequences(self, binary: str) -> int:\n # Set was used because there can be duplicates when we\n # go from, e.g. [1, 11] to [1, 11, 111]\n # 1 -> 11\n # 11 -> 111\n # [1, 11, 11, 111] -> [1, 11, 111]\n # However, the unique subsequences can be recorded as\n # number of sequences instead:\n # [1, 11] -> [1, 11, 111]\n # =>\n # 1 + len[11, 111] = 3\n \n # But that\'s only the case of a trailing one, when we meet\n # a zero, we do not need to add one becuase we don\'t need\n # to add the single 1 ahead.\n \n # And that will not work with a single dp field, because\n # the new values computed are classified as either trailing\n # 0 or 1, so the strategy is:\n \n # if binary[i] == \'1\':\n # dp_ones = dp_ones + dp_zeros + 1\n # else:\n # dp_zeros = dp_ones + dp_zeros\n \n # And that ignores the exception case of a single "0",\n # so add 1 to the result if "0" is present.\n \n mod = 10 ** 9 + 7\n zeros, ones = 0, 0\n \n for i in binary:\n if i == \'1\':\n ones += zeros + 1\n ones %= mod\n else:\n zeros += ones\n zeros %= mod\n\n return (zeros + ones + (\'0\' in binary)) % mod\n```
| 0 | 0 |
[]
| 0 |
lemonade-change
|
[C++/Java/Python] Straight Forward
|
cjavapython-straight-forward-by-lee215-w58k
|
Intuition:\nWhen the customer gives us $20, we have two options:\n1. To give three $5 in return\n2. To give one $5 and one $10.\n\nOn insight is that the second
|
lee215
|
NORMAL
|
2018-07-01T03:04:55.581649+00:00
|
2019-09-18T05:43:28.734281+00:00
| 28,807 | false |
## **Intuition**:\nWhen the customer gives us `$20`, we have two options:\n1. To give three `$5` in return\n2. To give one `$5` and one `$10`.\n\nOn insight is that the second option (if possible) is always better than the first one.\nBecause two `$5` in hand is always better than one `$10`\n<br>\n\n## **Explanation**:\nCount the number of `$5` and `$10` in hand.\n\nif (customer pays with `$5`) `five++`;\nif (customer pays with `$10`) `ten++, five--`;\nif (customer pays with `$20`) `ten--, five--` or `five -= 3`;\n\nCheck if five is positive, otherwise return false.\n<br>\n\n## **Time Complexity**\nTime `O(N)` for one iteration\nSpace `O(1)`\n<br>\n\n**C++:**\n```cpp\n int lemonadeChange(vector<int> bills) {\n int five = 0, ten = 0;\n for (int i : bills) {\n if (i == 5) five++;\n else if (i == 10) five--, ten++;\n else if (ten > 0) ten--, five--;\n else five -= 3;\n if (five < 0) return false;\n }\n return true;\n }\n```\n\n**Java:**\n```java\n public boolean lemonadeChange(int[] bills) {\n int five = 0, ten = 0;\n for (int i : bills) {\n if (i == 5) five++;\n else if (i == 10) {five--; ten++;}\n else if (ten > 0) {ten--; five--;}\n else five -= 3;\n if (five < 0) return false;\n }\n return true;\n }\n```\n**Python:**\n```py\n def lemonadeChange(self, bills):\n five = ten = 0\n for i in bills:\n if i == 5: five += 1\n elif i == 10: five, ten = five - 1, ten + 1\n elif ten > 0: five, ten = five - 1, ten - 1\n else: five -= 3\n if five < 0: return False\n return True\n```\n
| 373 | 5 |
[]
| 31 |
lemonade-change
|
Greedy Easy Solution | 1ms Beats 100%
|
greedy-easy-solution-1ms-beats-100-by-sa-5nt8
|
Complexity\n- Time complexity: O(N)\n\n- Space complexity:O(1)\n\n# Code\npython []\nclass Solution(object):\n def lemonadeChange(self, bills):\n if b
|
Sachinonly__
|
NORMAL
|
2024-08-15T00:26:05.752536+00:00
|
2024-08-15T00:26:05.752556+00:00
| 33,165 | false |
# Complexity\n- Time complexity: O(N)\n\n- Space complexity:O(1)\n\n# Code\n``` python []\nclass Solution(object):\n def lemonadeChange(self, bills):\n if bills[0] != 5:\n return False\n \n five_dollers = 0\n ten_dollers = 0\n\n for x in bills:\n if x == 5:\n five_dollers += 1\n elif x == 10:\n if five_dollers > 0:\n five_dollers -= 1\n else:\n return False\n ten_dollers += 1\n else:\n if five_dollers > 0 and ten_dollers > 0:\n five_dollers -= 1\n ten_dollers -= 1\n elif five_dollers > 2 :\n five_dollers -= 3\n else:\n return False\n print(five_dollers, ten_dollers)\n return True\n```\n```C++ []\nclass Solution {\npublic:\n bool lemonadeChange(vector<int>& bills) {\n int five_dollars = 0, ten_dollars = 0;\n \n for (int x : bills) {\n if (x == 5) {\n five_dollars++;\n } else if (x == 10) {\n if (five_dollars > 0) {\n five_dollars--;\n ten_dollars++;\n } else {\n return false;\n }\n } else {\n if (five_dollars > 0 && ten_dollars > 0) {\n five_dollars--;\n ten_dollars--;\n } else if (five_dollars > 2) {\n five_dollars -= 3;\n } else {\n return false;\n }\n }\n }\n \n return true;\n }\n};\n```\n```Java []\nclass Solution {\n public boolean lemonadeChange(int[] bills) {\n int five_dollars = 0, ten_dollars = 0;\n\n for (int x : bills) {\n if (x == 5) {\n five_dollars++;\n } else if (x == 10) {\n if (five_dollars > 0) {\n five_dollars--;\n ten_dollars++;\n } else {\n return false;\n }\n } else {\n if (five_dollars > 0 && ten_dollars > 0) {\n five_dollars--;\n ten_dollars--;\n } else if (five_dollars > 2) {\n five_dollars -= 3;\n } else {\n return false;\n }\n }\n }\n\n return true;\n }\n}\n```\n\n
| 186 | 2 |
['Array', 'Greedy', 'Python', 'C++', 'Java', 'Python3']
| 18 |
lemonade-change
|
Python simple & readable
|
python-simple-readable-by-cenkay-cq56
|
\nclass Solution:\n def lemonadeChange(self, bills):\n five = ten = 0\n for num in bills:\n if num == 5:\n five += 1\
|
cenkay
|
NORMAL
|
2018-07-01T03:34:21.198175+00:00
|
2018-10-25T13:34:32.868575+00:00
| 5,066 | false |
```\nclass Solution:\n def lemonadeChange(self, bills):\n five = ten = 0\n for num in bills:\n if num == 5:\n five += 1\n elif num == 10 and five:\n ten += 1\n five -= 1\n elif num == 20 and five and ten:\n five -= 1\n ten -= 1\n elif num == 20 and five >= 3:\n five -= 3\n else:\n return False\n return True\n```
| 39 | 1 |
[]
| 9 |
lemonade-change
|
C++/Java/Python || 🚀✅Fully Explained || 🚀✅Greedy Algo
|
cjavapython-fully-explained-greedy-algo-9b8qd
|
Intuition:\nThe problem requires us to simulate the process of giving change while selling lemonade. We have three types of bills of denominations 5, 10, and 20
|
devanshupatel
|
NORMAL
|
2023-04-24T19:55:42.818227+00:00
|
2023-04-24T20:43:14.991853+00:00
| 5,325 | false |
# Intuition:\nThe problem requires us to simulate the process of giving change while selling lemonade. We have three types of bills of denominations 5, 10, and 20. We need to keep track of the number of 5s and 10s we have at any moment to be able to give change for different bills. If at any moment, we don\'t have the required bills to give change, we return false.\n\n# Approach:\nWe use two variables fives and tens to keep track of the number of 5s and 10s we have. We initialize both of them to 0. We then iterate over the bills array and for each bill, we do the following:\n\n1. If the bill is of denomination 5, we increment the fives variable.\n2. If the bill is of denomination 10, we first check if we have at least one 5-dollar bill. If we don\'t have a 5-dollar bill, we can\'t give change, so we return false. If we have a 5-dollar bill, we decrement the fives variable and increment the tens variable.\n3. If the bill is of denomination 20, we first check if we have at least one 10-dollar bill and one 5-dollar bill. If we do, we decrement both the tens and fives variables. Otherwise, we check if\n4. we have at least three 5-dollar bills. If we do, we decrement the fives variable by 3. If we don\'t have enough bills to give change, we return false.\n5. At the end of the iteration, if we have not returned false, it means we were able to give change for all the bills and we can return true.\n\n# Complexity:\n- The time complexity of the algorithm is O(n), where n is the length of the bills array. We iterate over the array once. \n- The space complexity is O(1) because we are using only two variables fives and tens to keep track of the number of 5s and 10s we have.\n\n# Code\n# C++\n```\nclass Solution {\npublic:\n bool lemonadeChange(vector<int>& bills) {\n int fives = 0, tens = 0;\n for (int bill : bills) {\n if (bill == 5) {\n fives++;\n } else if (bill == 10) {\n if (fives == 0) {\n return false;\n }\n fives--;\n tens++;\n } else {\n if (tens > 0 && fives > 0) {\n tens--;\n fives--;\n } else if (fives >= 3) {\n fives -= 3;\n } else {\n return false;\n }\n }\n }\n return true;\n }\n};\n\n```\n# Java\n```\nclass Solution {\n public boolean lemonadeChange(int[] bills) {\n int fives = 0, tens = 0;\n for (int bill : bills) {\n if (bill == 5) {\n fives++;\n } else if (bill == 10) {\n if (fives == 0) {\n return false;\n }\n fives--;\n tens++;\n } else {\n if (tens > 0 && fives > 0) {\n tens--;\n fives--;\n } else if (fives >= 3) {\n fives -= 3;\n } else {\n return false;\n }\n }\n }\n return true;\n }\n}\n\n```\n# Python\n```\nclass Solution(object):\n def lemonadeChange(self, bills):\n fives, tens = 0, 0\n for bill in bills:\n if bill == 5:\n fives += 1\n elif bill == 10:\n if fives == 0:\n return False\n fives -= 1\n tens += 1\n else:\n if tens > 0 and fives > 0:\n tens -= 1\n fives -= 1\n elif fives >= 3:\n fives -= 3\n else:\n return False\n return True\n\n\n```\n# Thank You
| 35 | 1 |
['Array', 'Greedy', 'Python', 'C++', 'Java']
| 3 |
lemonade-change
|
C++ Easy and Simple Explained Solution, O(n) - faster than 100%
|
c-easy-and-simple-explained-solution-on-zkas3
|
\n// We just simulate the selling of lemonade.\nclass Solution {\npublic:\n bool lemonadeChange(vector<int>& bills) {\n int fives = 0, tens = 0;\n
|
yehudisk
|
NORMAL
|
2021-01-14T20:12:15.599378+00:00
|
2021-01-14T20:12:15.599420+00:00
| 3,177 | false |
```\n// We just simulate the selling of lemonade.\nclass Solution {\npublic:\n bool lemonadeChange(vector<int>& bills) {\n int fives = 0, tens = 0;\n for (auto bill : bills) {\n \n // first case - customer paid 5$ - no change needed\n if (bill == 5) \n fives++;\n \n // second case - customer paid 10$ - if we have a 5$ bill, give it. Otherwise - return false\n else if (bill == 10) {\n if (fives == 0) return false;\n tens++;\n fives--;\n }\n \n // third case - customer paid 20$ - if we have 5$ and 10$ bills - give that.\n // Else - if we have three 5$ bills - give that.\n // Otherwise - return false.\n else {\n if (fives > 0 && tens > 0) {\n fives--;\n tens--;\n }\n else if (fives >= 3) fives -= 3;\n else return false;\n }\n }\n return true;\n }\n};\n```\n**Like it? please upvote...**
| 21 | 0 |
['C']
| 3 |
lemonade-change
|
Greedy 1 loop vs recursion||40ms Beats 99.76%
|
greedy-1-loop-vs-recursion40ms-beats-997-5iwi
|
Intuition\n Describe your first thoughts on how to solve this problem. \ncount \$5, \$10 as possible returning change for bills. When b=20, the greedy algorithm
|
anwendeng
|
NORMAL
|
2024-08-15T01:08:07.763802+00:00
|
2024-08-15T14:13:45.171277+00:00
| 6,812 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\ncount \\$5, \\$10 as possible returning change for bills. When b=20, the greedy algorithm maintains the checking order. Give back \\$10 first, keep \\$5 as possible and do not change the checking order, otherwise it will not work.\n\n2nd approach uses recursion which is more concise.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n[Please Turn English subtitles if necessary]\n[https://youtu.be/nuOhP6F6MYc?si=sVMDgrCt5S3EXMRE](https://youtu.be/nuOhP6F6MYc?si=sVMDgrCt5S3EXMRE)\n1. Only \\$5, \\$10 need to be counted\n2. Use a loop to transverse & deal with 3 different cases\n3. Case of 5, cnt5+=1\n4. Case of 10, if cnt5>0: cnt5-=1, cnt10+=1 else return False\n5. Case of 20: 3 possiblities: Greedy algorithm keeps the checking order, never change the checking order otherwise it will not work\n```\nif (cnt10>0 && cnt5>0) cnt10--, cnt5--;\nelse if (cnt5>2) cnt5-=3;\nelse return 0;\n```\n6. 2nd approach is a recursive code; add some extra parameter to keep the code concise: `int i=0, int cnt5=0, int cnt10=0`\n# Testcase for checking Greedy Algorithm by real RUN\nConsider the testcase bills=`[5, 5, 5, 5, 10, 20, 10]`\nIf the checking order in case of b=20 is changed, it will be wrong.\nProcceed the 1st C++ by adding some output\n```\ncnt5=0, cnt10=0: Receive $5\ncnt5=1, cnt10=0: Receive $5\ncnt5=2, cnt10=0: Receive $5\ncnt5=3, cnt10=0: Receive $5\ncnt5=4, cnt10=0: Recieve $10, give back $5\ncnt5=3, cnt10=1: Receive $20, give back $5, $10\ncnt5=2, cnt10=0: Recieve $10, give back $5\n=>answer is correct\n```\nWhat if changing the order by giving back ` 3 $ 5 $then $ 10 + $ 5`?\n```\ncnt5=0, cnt10=0: Receive $5\ncnt5=1, cnt10=0: Receive $5\ncnt5=2, cnt10=0: Receive $5\ncnt5=3, cnt10=0: Receive $5\ncnt5=4, cnt10=0: Recieve $10, give back $5\ncnt5=3, cnt10=1: Receive $20, give back 3 $5\ncnt5=0, cnt10=1: Not enough change\n=>answer is wrong\n```\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\nrecursion:$O(n)$\n# Code||C++40ms Beats 99.76%\n```\nclass Solution {\npublic:\n static bool lemonadeChange(vector<int>& bills) {\n int cnt5=0, cnt10=0;\n for(int b: bills){\n switch(b){\n case 5: \n cnt5++; \n break;\n case 10: \n if (cnt5>0) cnt5--, cnt10++;\n else return 0;\n break;\n case 20:\n if (cnt10>0 && cnt5>0) cnt10--, cnt5--;\n else if (cnt5>2) cnt5-=3;\n else return 0;\n break;\n }\n }\n return 1;\n }\n};\n\n\n \nauto init = []() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n return \'c\';\n}();\n```\n# Python code done in video\n```\nclass Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n cnt5, cnt10=0, 0\n for b in bills:\n if b==5: cnt5+=1\n elif b==10:\n if cnt5>0:\n cnt5-=1\n cnt10+=1\n else:\n return False\n else:\n if cnt10>0 and cnt5>0:\n cnt10-=1\n cnt5-=1\n elif cnt5>2: cnt5-=3\n else: return False\n return True\n \n```\n# C++ recursion||65ms Beats 83.80%\n```\nclass Solution {\npublic:\n static bool lemonadeChange(vector<int>& bills, int i=0, int cnt5=0, int cnt10=0) {\n if (i==bills.size()) return cnt5>=0&&cnt10>=0;// base case\n if (cnt5<0 || cnt10<0 ) return 0;\n int b=bills[i];\n if (b==5) return lemonadeChange(bills, i+1, cnt5+1, cnt10);\n if (b==10) return lemonadeChange(bills, i+1, cnt5-1, cnt10+1);\n if (b==20 && cnt10>0) return lemonadeChange(bills, i+1, cnt5-1, cnt10-1);\n else return lemonadeChange(bills, i+1, cnt5-3, cnt10);\n }\n};\n```
| 20 | 1 |
['Array', 'Greedy', 'Recursion', 'C++', 'Python3']
| 9 |
lemonade-change
|
Python 97.19% faster | Simplest solution with explanation | Beg to Adv | Greedy
|
python-9719-faster-simplest-solution-wit-qtyz
|
python\nclass Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n count5 = 0 # taking counter for $5\n count10 = 0 # taking count
|
rlakshay14
|
NORMAL
|
2022-08-10T11:07:43.634897+00:00
|
2022-08-10T11:07:43.634927+00:00
| 2,656 | false |
```python\nclass Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n count5 = 0 # taking counter for $5\n count10 = 0 # taking counter for $10\n for b in bills: # treversing the list of bills.\n if b == 5: \n count5+=1 # if the bill is 5, incresing the 5 counter.\n elif b == 10:\n if count5 == 0: # if the bill is 10 & we dont have change to return, then its false.\n return False\n count10+=1 # increasing the 10 counter\n count5-=1 # decreasing 5 counter as we`ll give 5 as change. \n else: # if the bill is of $20\n if (count5>=1 and count10>=1):# checking if we have enough change to return\n count5-=1 # if its a $20 , then $5 as change and \n count10-=1 # one $10\n elif count5>=3: # fi we dont have $10 as change, though we have three $3.\n count5-=3 # decresing the $3 counter. \n else:\n return False\n return True\n \n ```\n***Found helpful, Do upvote !!***\n
| 20 | 0 |
['Greedy', 'Python', 'Python3']
| 1 |
lemonade-change
|
JAVA QUESTION AND ANSWER CLEARLY EXPLAINED
|
java-question-and-answer-clearly-explain-76jo
|
ok lets do this!\nfirst understand the question correctly:\nbasically we are the lemonade shop owner and the customer pays us either a $5 or $10 or $20 to buy a
|
naturally_aspirated
|
NORMAL
|
2020-05-21T18:59:35.293723+00:00
|
2020-05-21T18:59:35.293757+00:00
| 2,288 | false |
ok lets do this!\nfirst understand the question correctly:\nbasically we are the lemonade shop owner and the customer pays us either a $5 or $10 or $20 to buy a lemonade whose cost is constant- $5 \n\n**This is a greedy problem because at each step we are greedily giving the change back to the customer in such a manner that we have maximum number of $5 bills with us!**\n\nbecause consider the situation when the customer gives us $20 and we have two $10 bills!\nin such a case we are unable to give back the change to the customer!\nOn the otherhand if we had four $5 bills or one $10 and two $5 bills then we can give back the change to the customer!\n\nSo our aim is to maximise the number if $5 bills!\n\nsee the code below \ncomments are added to clearly explain the conditions!\n\n```\nclass Solution {\n public boolean lemonadeChange(int[] bills) {\n int five = 0, ten = 0;\n for (int i : bills) {\n if (i == 5) //if customer gives $5 then we simply take it as lemonade costs $5 \n five++;\n else if (i == 10) { //if we have $10 then we reduce number of $5 bills by one and increase $10 by one\n five--; ten++;\n }\n else if (ten > 0 && five>=1) { //if we get $20 then we first try to give back $10+$5\n ten--; five--;\n }\n else // if we cannot give back $10+$5 then unfortunately we have to give back $5+$5+$5\n five -= 3;\n if (five < 0) // if at any time we do not have any $5 left then we return false\n return false;\n }\n return true;\n }\n \n} \n```\n\nHOPE IT HELPS!\n\n \n\n
| 19 | 0 |
['Java']
| 2 |
lemonade-change
|
✅Easy and Clean Code (C++ / Java)✅
|
easy-and-clean-code-c-java-by-sourav_n06-552k
|
Intuition:\n\n- Smallest Denomination First: When trying to give change, prefer to give out the largest bills first (e.g., give a $10 bill when possible) becaus
|
sourav_n06
|
NORMAL
|
2024-08-15T04:22:14.971274+00:00
|
2024-08-15T04:23:03.178313+00:00
| 4,549 | false |
### Intuition:\n\n- **Smallest Denomination First:** When trying to give change, prefer to give out the largest bills first (e.g., give a $10 bill when possible) because this leaves more $5 bills available for future transactions. This strategy maximizes your chances of being able to provide the correct change in subsequent transactions.\n \n- **Tracking State Efficiently:** The use of a map (or an array for a small number of denominations) is efficient for tracking the number of each bill. This approach ensures that each lookup and update operation is done in constant time, making the solution efficient even for large inputs.\n\n- **Edge Cases:** The solution naturally handles edge cases such as running out of $5 bills early or being unable to provide change for a $20 bill. The early return of `false` ensures that you stop processing as soon as you can\'t meet the requirements, making the function efficient.\n\nThis approach ensures that you can handle a variety of payment scenarios while minimizing the chances of running out of the necessary bills to provide change.\n\n### Approach:\n\n1. **Initialize Tracking Variables:**\n - Use a `HashMap` (or in C++, an `unordered_map`) to track the number of $5 and $10 bills you have. This map will help you determine whether you can provide the correct change when customers pay with larger bills.\n \n2. **Iterate Over the Bills:**\n - Loop through each bill in the `bills` array (or vector in C++).\n - For each bill, calculate the change needed by subtracting $5 from the bill value (since each lemonade costs $5).\n\n3. **Handle Different Cases:**\n - **Case 1:** The bill is $5:\n - No change is needed. Simply increment the count of $5 bills in the map.\n - **Case 2:** The bill is $10:\n - The customer needs $5 as change. Check if there\'s a $5 bill available in the map.\n - If yes, decrement the count of $5 bills and add the $10 bill to the map.\n - If no, return `false` because you can\'t provide the correct change.\n - **Case 3:** The bill is $20:\n - The customer needs $15 as change. This can be given in two ways:\n 1. **Preferred:** One $10 bill and one $5 bill. Check if both are available.\n 2. **Fallback:** Three $5 bills if the first option is not possible.\n - If neither option is possible, return `false`.\n\n4. **Return Result:**\n - If the loop completes without returning `false`, it means you were able to provide the correct change for all customers. Return `true`.\n\n\n# Complexity\n- Time complexity: O(N) \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1) \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nbecause HashMap will always take size 3 only it does not depends on N\nwhere N is size of bills.\n# Code\n```C++ []\nclass Solution {\npublic:\n bool lemonadeChange(vector<int>& bills) {\n unordered_map<int, int> track;\n int netBal = 0;\n for(auto bill : bills) {\n int change = bill - 5;\n if (change == 5) {\n if(track[5] == 0) return false;\n else track[5]--;\n } \n else if (change == 15) {\n if (track[5] >= 1 && track[10] >= 1) {\n track[5]--;\n track[10]--;\n }\n else if (track[5] >= 3) track[5] += -3;\n else return false;\n }\n track[bill]++;\n }\n return true;\n }\n};\n```\n```Java []\nclass Solution {\n public boolean lemonadeChange(int[] bills) {\n Map<Integer, Integer> track = new HashMap<>();\n\n for (int bill : bills) {\n int change = bill - 5;\n\n if (change == 5) {\n if (track.getOrDefault(5, 0) == 0) {\n return false;\n } else {\n track.put(5, track.get(5) - 1);\n }\n } else if (change == 15) {\n if (track.getOrDefault(5, 0) >= 1 && track.getOrDefault(10, 0) >= 1) {\n track.put(5, track.get(5) - 1);\n track.put(10, track.get(10) - 1);\n } else if (track.getOrDefault(5, 0) >= 3) {\n track.put(5, track.get(5) - 3);\n } else {\n return false;\n }\n }\n\n track.put(bill, track.getOrDefault(bill, 0) + 1);\n }\n\n return true;\n }\n}\n\n```\n\n\n\n
| 18 | 0 |
['Array', 'Greedy', 'C++', 'Java']
| 6 |
lemonade-change
|
✅ [Solution] Swift: Lemonade Change
|
solution-swift-lemonade-change-by-asahio-zynv
|
swift\nclass Solution {\n func lemonadeChange(_ bills: [Int]) -> Bool {\n var five = 0, ten = 0\n for b in bills {\n switch b {\n
|
AsahiOcean
|
NORMAL
|
2021-05-31T01:35:29.061121+00:00
|
2022-03-29T18:32:28.756026+00:00
| 996 | false |
```swift\nclass Solution {\n func lemonadeChange(_ bills: [Int]) -> Bool {\n var five = 0, ten = 0\n for b in bills {\n switch b {\n case 5:\n five += 1\n case 10:\n ten += 1\n if five < 1 { return false }\n five -= 1\n case 20:\n if five < 1 || ten < 1, five < 3 { return false }\n if ten >= 1 { ten -= 1; five -= 1 } else { five -= 3 }\n default: break\n }\n }\n return true\n }\n}\n```\n\n<hr>\n\n<details>\n<summary><img src="https://git.io/JDblm" height="24"> <b>TEST CASES</b></summary>\n\n<pre>\nResult: Executed 2 tests, with 0 failures (0 unexpected) in 0.008 (0.010) seconds\n</pre>\n\n```swift\nimport XCTest\n\nclass Tests: XCTestCase {\n \n private let solution = Solution()\n \n /*\n From the first 3 customers, we collect three $5 bills in order.\n From the fourth customer, we collect a $10 bill and give back a $5.\n From the fifth customer, we give a $10 bill and a $5 bill.\n Since all customers got correct change, we output true.\n */\n func test0() {\n let value = solution.lemonadeChange([5,5,5,10,20])\n XCTAssertEqual(value, true)\n }\n \n /*\n From the first two customers in order, we collect two $5 bills.\n For the next two customers in order, we collect a $10 bill and give back a $5 bill.\n For the last customer, we can not give the change of $15 back because we only have two $10 bills.\n Since not every customer received the correct change, the answer is false.\n */\n func test1() {\n let value = solution.lemonadeChange([5,5,10,10,20])\n XCTAssertEqual(value, false)\n }\n}\n\nTests.defaultTestSuite.run()\n```\n\n</details>
| 12 | 0 |
['Swift']
| 0 |
lemonade-change
|
💢☠💫Easiest 🎯 C++✅Python3🐍✅Java✅C✅Python🐍✅C#✅💥🔥💫Explained☠💥🔥 Beats 💯
|
easiestfaster-lesser-cpython3javacpython-93ur
|
Intuition
ApproachComplexity
Time complexity:
Space complexity:
Code
|
Edwards310
|
NORMAL
|
2024-08-15T10:54:09.025199+00:00
|
2025-01-01T10:51:32.735885+00:00
| 1,240 | false |
# Intuition








```javascript []
//JavaScript Code
/**
* @param {number[]} bills
* @return {boolean}
*/
var lemonadeChange = function(bills) {
let five = 0, ten = 0;
for(let bill of bills) {
if( bill == 5)
five++;
else if( bill == 10) {
if( five >= 1) {
five--;
ten++;
}
else
return false;
}
else {
if(five >= 1 && ten >= 1) {
ten--;
five--;
}
else if( five >= 3)
five -= 3;
else
return false;
}
}
return true;
};
```
```python3 []
#Python3 Code
class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
cur_five, cur_ten = 0, 0
for doller in bills:
if doller == 5:
cur_five += 1
elif doller == 10:
cur_five -= 1
cur_ten += 1
elif cur_ten > 0:
cur_ten -= 1
cur_five -= 1
else:
cur_five -= 3
if cur_five < 0:
return False
return True
```
```C++ []
//C++ Code
#pragma GCC optimize("O2")
#include <bits/stdc++.h>
using namespace std;
typedef vector<int> vi;
typedef vector<vi> vvi;
#define FOR(a, b, c) for (int a = b; a < c; a++)
#define FOR1(a, b, c) for (int a = b; a <= c; ++a)
#define Rep(i, n) FOR(i, 0, n)
#define Rep1(i, n) FOR1(i, 1, n)
#define RepA(ele, nums) for (auto& ele : nums)
#define WHL(i, n) while (i < n)
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define ALL(v) v.begin(), v.end()
#define SORT(v) sort(ALL(v))
class Solution {
public:
bool lemonadeChange(vector<int>& bills) {
int five = 0, ten = 0;
RepA(bill, bills) {
if( bill == 5)
five++;
else if( bill == 10) {
if( five >= 1) {
five--;
ten++;
}
else
return false;
}
else {
if(five >= 1 && ten >= 1) {
ten--;
five--;
}
else if( five >= 3)
five -= 3;
else
return false;
}
}
return true;
}
};
```
```Java []
//Java Code
class Solution {
public boolean lemonadeChange(int[] bills) {
int five = 0, ten = 0;
for (int bill : bills) {
if( bill == 5)
five++;
else if( bill == 10) {
if( five >= 1) {
five--;
ten++;
}
else
return false;
}
else {
if(five >= 1 && ten >= 1) {
ten--;
five--;
}
else if( five >= 3)
five -= 3;
else
return false;
}
}
return true;
}
}
```
```C []
//C Code
bool lemonadeChange(int* bills, int billsSize) {
int five = 0, ten = 0;
for(int i = 0; i < billsSize; i++) {
int bill = bills[i];
if( bill == 5)
five++;
else if( bill == 10) {
if( five >= 1) {
five--;
ten++;
}
else
return false;
}
else {
if(five >= 1 && ten >= 1) {
ten--;
five--;
}
else if( five >= 3)
five -= 3;
else
return false;
}
}
return true;
}
```
```Python []
#Python Code
class Solution(object):
def lemonadeChange(self, bills):
"""
:type bills: List[int]
:rtype: bool
"""
f , t = 0, 0
for bill in bills:
if bill == 5:
f += 1
elif bill == 10:
if f >= 1:
f -= 1
t += 1
else:
return False
else:
if f >= 1 and t >= 1:
t -= 1
f -= 1
elif f >= 3:
f -= 3
else:
return False
return True
```
```C# []
//C# Code
public class Solution {
public bool LemonadeChange(int[] bills) {
int five = 0, ten = 0;
foreach(var bill in bills) {
if( bill == 5)
five++;
else if( bill == 10) {
if( five >= 1) {
five--;
ten++;
}
else
return false;
}
else {
if(five >= 1 && ten >= 1) {
ten--;
five--;
}
else if( five >= 3)
five -= 3;
else
return false;
}
}
return true;
}
}
```
``` Go []
func lemonadeChange(bills []int) bool {
five, ten := 0, 0
for _, bill := range bills {
if bill == 5 {
five++
} else if bill == 10 {
if five >= 1 {
five--
ten++
} else {
return false
}
} else {
if five >= 1 && ten >= 1 {
five--
ten--
} else if five >= 3 {
five -= 3
} else {
return false
}
}
}
return true
}
```
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
O(n)
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
O(1)
# Code

| 11 | 0 |
['Array', 'Greedy', 'C', 'Python', 'C++', 'Java', 'Go', 'Python3', 'JavaScript', 'C#']
| 1 |
lemonade-change
|
O(n) | Stack | Greedy | Java | C++ | Python | Go | Rust | JavaScript
|
on-stack-greedy-java-c-python-go-rust-ja-zeeo
|
\n# Approach 1\n### Intuition\n\nImagine you\u2019re running a lemonade stand on a hot summer day. The lemonade is priced at 5 dollars per cup, and customers ar
|
kartikdevsharma_
|
NORMAL
|
2024-08-14T06:16:23.570043+00:00
|
2024-08-18T18:17:13.563262+00:00
| 1,804 | false |
\n# Approach 1\n### Intuition\n\nImagine you\u2019re running a lemonade stand on a hot summer day. The lemonade is priced at 5 dollars per cup, and customers are lining up to quench their thirst. However, not everyone has exact change, and you start the day with an empty cash box. Your challenge is to determine if you can successfully operate your stand throughout the day, providing correct change to every customer, given the sequence of bills they\u2019ll present.\n\nThe tricky part is, we start with no change in our pocket. So we\'ve got to figure out if we can make change for everyone as they come up to buy lemonade. If we can\'t make change even once, we\'re in trouble and have to close up shop.\n\nWhen I first looked at this problem, I thought, this is all about keeping track of the money we have and making smart decisions about how to give change. It\'s like a puzzle where each customer is a new piece, and we have to fit it in just right.\n\nThe key here is to think ahead. We need to hold onto smaller bills when we can, because they\'re going to be super useful for making change later. It\'s kind of like playing chess - you\'ve got to think a few moves ahead.\n\n## Approach\n### Step 1: State Representation\n\nThe first decision we need to make is how to represent the state of our cash box. We could use a variety of data structures, but let\'s consider what information is truly necessary:\n\n1. We need to know how many 5 dollar bills we have.\n2. We need to know how many 10 dollar bills we have.\n3. Do we need to keep track of 20 dollar bills?\n\nAfter careful consideration, we realize that we don\'t need to keep track of 20 dollar bills. Why? Because we never use them to make change. Once we receive a 20 dollar bill, it stays in our cash box and doesn\'t affect our ability to make change for future customers.\n\nSo, our state can be represented by just two integers:\n- `fives`: The number of 5 dollar bills we have.\n- `tens`: The number of 10 dollar bills we have.\n\nThis simple state representation is sufficient to solve the problem and leads to an efficient solution with minimal space complexity.\n\n### Step 2: Processing Transactions\n\nNow that we have our state representation, let\'s consider how to process each transaction. We\'ll need to handle three cases:\n\n1. Customer pays with a 5 dollar bill:\n This is the simplest case. We don\'t need to give any change, so we just add the 5 dollar bill to our count of fives.\n\n2. Customer pays with a 10 dollar bill:\n We need to give 5 dollars in change. To do this, we need at least one 5 dollar bill. If we have one, we can make the change by decrementing our count of fives and incrementing our count of tens. If we don\'t have a 5 dollar bill, we can\'t make change, and we need to close the stand.\n\n3. Customer pays with a 20 dollar bill:\n This is the most complex case. We need to give 15 dollars in change. We have two options:\n a. Give one 10 dollar bill and one 5 dollar bill.\n b. Give three 5 dollar bills.\n\n We prefer option (a) when possible because it allows us to keep more 5 dollar bills, which are more flexible for making change. If we can\'t do (a), we try (b). If we can\'t do either, we need to close the stand.\n\n### Step 3: The Greedy Choice\n\nIn the case of a 20 dollar bill, we\'re making a greedy choice by preferring to give a 10 dollar bill and a 5 dollar bill as change. This choice is greedy because it\'s the best option for our current transaction (it leaves us with more 5 dollar bills), but we\'re not considering future transactions.\n\nWhy is this greedy choice actually optimal? Because 5 dollar bills are the most versatile for making change. By keeping as many 5 dollar bills as possible, we maximize our ability to make change for future transactions.\n\n### Step 4: Implementing the Algorithm\n\nNow, let\'s talk about how we\'re going to tackle this problem step by step.\n\n1. First things first, we\'re going to create a `LemonadeStand` class. This class is going to be our lemonade stand in code form. It\'s going to keep track of all our money and handle all our transactions.\n\n2. Inside this class, we\'re going to have two important variables:\n - `fives`: This is going to count how many 5 dollar bills we have.\n - `tens`: This is going to count how many 10 dollar bills we have.\n\n Notice we don\'t bother counting 20 dollar bills. Why? Because we never use them to make change. They just sit in our cash box looking pretty.\n\n3. Now, we\'re going to create a method called `canProvideChange`. This method is going to take an array of all the bills our customers are going to give us throughout the day. It\'s like being able to see into the future and know exactly what everyone\'s going to pay with.\n\n4. Inside `canProvideChange`, we\'re going to go through each bill one by one. For each bill, we\'re going to call another method called `processTransaction`. This method is where the magic happens - it\'s going to handle each individual sale.\n\n5. Let\'s break down `processTransaction`:\n - If someone gives us a 5 dollar bill, awesome! We just add it to our count of fives and move on.\n - If someone gives us a 10 dollar bill, we need to give them 5 dollars change. So we check if we have any 5 dollar bills. If we do, great! We give them one 5 dollar bill (by decreasing our `fives` count) and add their 10 to our `tens` count. If we don\'t have a 5 dollar bill, uh-oh! We can\'t make change, so we return `false`.\n - If someone gives us a 20 dollar bill, things get a bit more complicated. We need to give them 15 dollars in change. For this, we call another method called `provideChangeFor20`.\n\n6. In `provideChangeFor20`, we have two options:\n - Option 1: Give them one 10 dollar bill and one 5 dollar bill. This is our preferred option because it lets us hold onto more 5 dollar bills, which are super useful.\n - Option 2: If we don\'t have a 10 dollar bill (or not enough 5 dollar bills), we can give them three 5 dollar bills.\n - If we can\'t do either of these, we\'re out of luck and have to return `false`.\n\n7. If at any point during all these transactions we can\'t make change (meaning `processTransaction` returns `false`), we immediately stop and say we can\'t provide change for everyone (by returning `false` from `canProvideChange`).\n\n8. If we make it through all the transactions without any problems, hooray! We return `true` because we successfully gave everyone their lemonade and correct change.\n\nIn this approach We\'re always trying to make the best decision right now, without worrying too much about the future. But because we prefer to give 10 dollar bills as change when we can, we\'re actually setting ourselves up for success in the future too.\n\n### Complexity\n\nNow, let\'s talk about how efficient this solution is.\n\n **Time complexity: O(n)**\n Here\'s why: We go through each bill in the input array exactly once. No matter how many bills there are, we only look at each one a single time. So if there are n bills, we do about n operations. This is what we call linear time complexity, or O(n).\n\n- The `canProvideChange` method goes through each bill once: O(n)\n- For each bill, we call `processTransaction`, which is O(1) because it just does a few simple operations\n- `provideChangeFor20` is also O(1) for the same reason\n- So, overall, we\'re doing O(1) work n times, which gives us O(n)\n\n **Space complexity: O(1)**\n This is the really cool part. No matter how many customers we have or how many bills they give us, we only ever use two variables to keep track of our money (`fives` and `tens`). We don\'t create any new data structures that grow with the input size. This is what we call constant space complexity, or O(1).\n\n- We only use two integer variables (`fives` and `tens`) regardless of input size\n- We don\'t create any arrays, lists, or other data structures that grow with input\n- So our space usage is constant, giving us O(1)\n\n\n\n\n\n### Code\n```Java []\nclass LemonadeStand {\n private int fives = 0;\n private int tens = 0;\n\n public boolean canProvideChange(int[] customerBills) {\n for (int bill : customerBills) {\n if (!processTransaction(bill)) {\n return false;\n }\n }\n return true;\n }\n\n private boolean processTransaction(int bill) {\n switch (bill) {\n case 5:\n fives++;\n return true;\n case 10:\n if (fives == 0) return false;\n fives--;\n tens++;\n return true;\n case 20:\n return provideChangeFor20();\n default:\n throw new IllegalArgumentException("Invalid bill: " + bill);\n }\n }\n\n private boolean provideChangeFor20() {\n if (tens > 0 && fives > 0) {\n tens--;\n fives--;\n } else if (fives >= 3) {\n fives -= 3;\n } else {\n return false;\n }\n return true;\n }\n}\n\n\nclass Solution {\n public boolean lemonadeChange(int[] bills) {\n return new LemonadeStand().canProvideChange(bills);\n }\n}\n```\n```C++ []\nclass LemonadeStand {\nprivate:\n int fives = 0;\n int tens = 0;\n\n bool processTransaction(int bill) {\n switch (bill) {\n case 5:\n fives++;\n return true;\n case 10:\n if (fives == 0) return false;\n fives--;\n tens++;\n return true;\n case 20:\n return provideChangeFor20();\n default:\n throw std::invalid_argument("Invalid bill");\n }\n }\n\n bool provideChangeFor20() {\n if (tens > 0 && fives > 0) {\n tens--;\n fives--;\n } else if (fives >= 3) {\n fives -= 3;\n } else {\n return false;\n }\n return true;\n }\n\npublic:\n bool canProvideChange(std::vector<int>& bills) {\n for (int bill : bills) {\n if (!processTransaction(bill)) {\n return false;\n }\n }\n return true;\n }\n};\n\nclass Solution {\npublic:\n bool lemonadeChange(std::vector<int>& bills) {\n return LemonadeStand().canProvideChange(bills);\n }\n};\n```\n```Python []\nclass LemonadeStand:\n def __init__(self):\n self.fives = 0\n self.tens = 0\n\n def can_provide_change(self, bills):\n for bill in bills:\n if not self.process_transaction(bill):\n return False\n return True\n\n def process_transaction(self, bill):\n if bill == 5:\n self.fives += 1\n return True\n elif bill == 10:\n if self.fives == 0:\n return False\n self.fives -= 1\n self.tens += 1\n return True\n elif bill == 20:\n return self.provide_change_for_20()\n else:\n raise ValueError("Invalid bill")\n\n def provide_change_for_20(self):\n if self.tens > 0 and self.fives > 0:\n self.tens -= 1\n self.fives -= 1\n elif self.fives >= 3:\n self.fives -= 3\n else:\n return False\n return True\n\nclass Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n return LemonadeStand().can_provide_change(bills)\n```\n```Go []\npackage main\n\ntype LemonadeStand struct {\n fives int\n tens int\n}\n\nfunc (ls *LemonadeStand) canProvideChange(bills []int) bool {\n for _, bill := range bills {\n if !ls.processTransaction(bill) {\n return false\n }\n }\n return true\n}\n\nfunc (ls *LemonadeStand) processTransaction(bill int) bool {\n switch bill {\n case 5:\n ls.fives++\n return true\n case 10:\n if ls.fives == 0 {\n return false\n }\n ls.fives--\n ls.tens++\n return true\n case 20:\n return ls.provideChangeFor20()\n default:\n \n return false\n }\n}\n\nfunc (ls *LemonadeStand) provideChangeFor20() bool {\n if ls.tens > 0 && ls.fives > 0 {\n ls.tens--\n ls.fives--\n } else if ls.fives >= 3 {\n ls.fives -= 3\n } else {\n return false\n }\n return true\n}\n\nfunc lemonadeChange(bills []int) bool {\n stand := &LemonadeStand{}\n return stand.canProvideChange(bills)\n}\n```\n```Rust []\nstruct LemonadeStand {\n fives: i32,\n tens: i32,\n}\n\nimpl LemonadeStand {\n fn new() -> Self {\n LemonadeStand { fives: 0, tens: 0 }\n }\n\n fn can_provide_change(&mut self, bills: Vec<i32>) -> bool {\n for bill in bills {\n if !self.process_transaction(bill) {\n return false;\n }\n }\n true\n }\n\n fn process_transaction(&mut self, bill: i32) -> bool {\n match bill {\n 5 => {\n self.fives += 1;\n true\n }\n 10 => {\n if self.fives == 0 {\n return false;\n }\n self.fives -= 1;\n self.tens += 1;\n true\n }\n 20 => self.provide_change_for_20(),\n _ => false, \n }\n }\n\n fn provide_change_for_20(&mut self) -> bool {\n if self.tens > 0 && self.fives > 0 {\n self.tens -= 1;\n self.fives -= 1;\n } else if self.fives >= 3 {\n self.fives -= 3;\n } else {\n return false;\n }\n true\n }\n}\n\n\n\nimpl Solution {\n pub fn lemonade_change(bills: Vec<i32>) -> bool {\n LemonadeStand::new().can_provide_change(bills)\n }\n}\n```\n```JavaScript []\nclass LemonadeStand {\n constructor() {\n this.fives = 0;\n this.tens = 0;\n }\n\n canProvideChange(bills) {\n for (let bill of bills) {\n if (!this.processTransaction(bill)) {\n return false;\n }\n }\n return true;\n }\n\n processTransaction(bill) {\n switch (bill) {\n case 5:\n this.fives++;\n return true;\n case 10:\n if (this.fives === 0) return false;\n this.fives--;\n this.tens++;\n return true;\n case 20:\n return this.provideChangeFor20();\n default:\n throw new Error("Invalid bill");\n }\n }\n\n provideChangeFor20() {\n if (this.tens > 0 && this.fives > 0) {\n this.tens--;\n this.fives--;\n } else if (this.fives >= 3) {\n this.fives -= 3;\n } else {\n return false;\n }\n return true;\n }\n}\n\n/**\n * @param {number[]} bills\n * @return {boolean}\n */\nvar lemonadeChange = function(bills) {\n return new LemonadeStand().canProvideChange(bills);\n};\n\n```\n---\n# Approach 2\n\n\n\n### Intuition\n\nYou know how when you\'re dealing with cash, you sometimes stack bills of the same denomination together? That\'s essentially what we\'re doing here, but in code. Instead of just counting how many of each bill we have, we\'re actually keeping them in separate stacks.\n\nPicture this: You\'ve got two stacks of bills on your lemonade stand counter. One stack is for 5 dollar bills, and another for 10 dollar bills. Every time you get a new bill, you put it on top of the appropriate stack. When you need to make change, you take bills off the top of these stacks.\n\nThis stack idea came to me when I was thinking about how we handle money in real life. We don\'t just keep a mental count; we physically organize our cash. This approach mimics that real-world behavior more closely.\n\n### Approach\n \nLet\'s break down into more detail.\n\n1. **Initialize the Cash Box**\n\nWe start by setting up our virtual cash box. In the real world, we might have two compartments in our cash drawer - one for 5-dollar bills and another for 10-dollar bills. In our code, we\'ll represent these compartments as stacks.\n\n```\nfunction lemonadeChange(bills):\n create empty stack fives\n create empty stack tens\n```\n\nThese stacks will operate on the Last-In-First-Out (LIFO) principle, just like how you\'d naturally stack bills in a real cash box. The last bill you put in is the first one you\'d take out when making change.\n\n2. **Process Each Customer**\n\nNow, we\'ll go through each customer\'s payment one by one. We\'ll use a loop to iterate through the \'bills\' array.\n\n```\n for each bill in bills:\n if canMakeChange(bill):\n continue\n else:\n return false\n```\n\nHere, we\'re checking if we can make change for each customer. If we can\'t make change for even one customer, we immediately return false because we\'ve failed our task.\n\n3. **Handling Different Bill Denominations**\n\nLet\'s break down the `canMakeChange` function:\n\n```\nfunction canMakeChange(bill):\n if bill is 5:\n push 5 onto fives stack\n return true\n else if bill is 10:\n if fives is empty:\n return false\n pop from fives stack\n push 10 onto tens stack\n return true\n else if bill is 20:\n return makeChangeFor20()\n else:\n throw error "Invalid bill denomination"\n```\n\nLet\'s examine each case:\n\n- a) 5-dollar bill:\n This is the simplest case. We don\'t need to make any change, we just add the 5-dollar bill to our fives stack. It\'s like saying, "Thanks for the exact change!" and putting the bill in our cash box.\n\n- b) 10-dollar bill:\n Here\'s where it gets interesting. The customer is overpaying by 5 dollars, so we need to give them 5 dollars back. We first check if we have any 5-dollar bills. If we don\'t, we\'re in trouble - we can\'t make change, so we return false. If we do have a 5-dollar bill, we remove it from our fives stack (that\'s the \'pop\' operation) and give it to the customer. Then we add the 10-dollar bill to our tens stack.\n\n- c) 20-dollar bill:\n This is the most complex case, so we\'ve separated it into its own function. Let\'s look at that next.\n\n4. **Making Change for a 20-dollar Bill**\n\nHere\'s where our stack approach really shines. We have two possible ways to make 15 dollars in change: one 10-dollar bill and one 5-dollar bill, or three 5-dollar bills. We\'ll try these options in order.\n\n```\nfunction makeChangeFor20():\n if tens is not empty and fives is not empty:\n pop from tens stack\n pop from fives stack\n return true\n else if size of fives stack is at least 3:\n pop from fives stack\n pop from fives stack\n pop from fives stack\n return true\n else:\n return false\n```\n\nLet\'s break this down:\n\na) First, we check if we have both a 10-dollar bill and a 5-dollar bill. If we do, we use those to make change. We remove one bill from each stack.\n\nb) If we don\'t have that combination, we check if we have at least three 5-dollar bills. If we do, we use those, removing three bills from the fives stack.\n\nc) If we can\'t do either of these, we\'re out of luck. We can\'t make change, so we return false.\n\nThis approach mimics how you might actually make change in real life. You\'d first look for the larger bill to make change more quickly, and only break it down into smaller bills if you have to.\n\n5. **Completing the Transaction**\n\nIf we\'ve made it through all the customers without returning false, it means we successfully gave everyone correct change. So we return true at the end of our main function.\n\n```\n return true // We\'ve successfully served all customers\n```\n\n\n\n\n### Complexity\n\n\n\n- **Time complexity: O(n)**\n We\'re still processing each customer exactly once, where n is the number of customers (or the length of the `bills` array). Each operation (pushing or popping from a stack) is O(1), so our overall time complexity remains linear.\n\n- **Space complexity: O(n)**\n This is where our stack approach differs from the counter approach. In the worst case, if all customers pay with 5 dollar bills, we\'ll end up with a stack of n 5 dollar bills. So our space complexity is O(n).\n\n However, it\'s worth noting that in practice, our space usage will often be much less than n. We\'re only storing 5 dollar and 10 dollar bills, and we\'re using them to make change as we go. So unless we have a long string of 5 dollar payments, our stacks won\'t grow too large.\n\n\n\n\n### Code\n\n\n \n```Java []\nclass Solution {\n public boolean lemonadeChange(int[] bills) {\n Stack<Integer> fives = new Stack<>();\n Stack<Integer> tens = new Stack<>();\n \n for (int bill : bills) {\n if (bill == 5) {\n fives.push(5);\n } else if (bill == 10) {\n if (fives.isEmpty()) return false;\n fives.pop();\n tens.push(10);\n } else if (bill == 20) {\n if (!tens.isEmpty() && !fives.isEmpty()) {\n tens.pop();\n fives.pop();\n } else if (fives.size() >= 3) {\n fives.pop();\n fives.pop();\n fives.pop();\n } else {\n return false;\n }\n }\n }\n return true;\n }\n}\n\n```\n\n```C++ []\nclass Solution {\npublic:\n bool lemonadeChange(vector<int>& bills) {\n int fives = 0, tens = 0;\n for (int bill : bills) {\n if (bill == 5) {\n fives++;\n } else if (bill == 10) {\n if (fives == 0) return false;\n fives--;\n tens++;\n } else { // bill == 20\n if (tens > 0 && fives > 0) {\n tens--;\n fives--;\n } else if (fives >= 3) {\n fives -= 3;\n } else {\n return false;\n }\n }\n }\n return true;\n }\n};\n```\n\n```Python []\nclass Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n fives, tens = 0, 0\n \n for bill in bills:\n if bill == 5:\n fives += 1\n elif bill == 10:\n if fives == 0:\n return False\n fives -= 1\n tens += 1\n elif bill == 20:\n if tens > 0 and fives > 0:\n tens -= 1\n fives -= 1\n elif fives >= 3:\n fives -= 3\n else:\n return False\n else:\n return False # Invalid bill\n \n return True\n\ns = Solution()\nwith open(\'user.out\', \'w\') as f:\n for case in map(json.loads, stdin):\n result = s.lemonadeChange(case)\n f.write(f"{str(result).lower()}\\n")\n\nexit(0)\n```\n```Go []\nfunc lemonadeChange(bills []int) bool {\n fives, tens := 0, 0\n for _, bill := range bills {\n if bill == 5 {\n fives++\n } else if bill == 10 {\n if fives == 0 {\n return false\n }\n fives--\n tens++\n } else { // bill == 20\n if tens > 0 && fives > 0 {\n tens--\n fives--\n } else if fives >= 3 {\n fives -= 3\n } else {\n return false\n }\n }\n }\n return true\n}\n```\n\n```Rust []\nimpl Solution {\n pub fn lemonade_change(bills: Vec<i32>) -> bool {\n let mut fives = 0;\n let mut tens = 0;\n for bill in bills {\n match bill {\n 5 => fives += 1,\n 10 => {\n if fives == 0 {\n return false;\n }\n fives -= 1;\n tens += 1;\n }\n 20 => {\n if tens > 0 && fives > 0 {\n tens -= 1;\n fives -= 1;\n } else if fives >= 3 {\n fives -= 3;\n } else {\n return false;\n }\n }\n _ => unreachable!(),\n }\n }\n true\n }\n}\n```\n```JavaScript []\n/**\n * @param {number[]} bills\n * @return {boolean}\n */\nvar lemonadeChange = function(bills) {\n let fives = 0, tens = 0;\n for (let bill of bills) {\n if (bill === 5) {\n fives++;\n } else if (bill === 10) {\n if (fives === 0) return false;\n fives--;\n tens++;\n } else { // bill === 20\n if (tens > 0 && fives > 0) {\n tens--;\n fives--;\n } else if (fives >= 3) {\n fives -= 3;\n } else {\n return false;\n }\n }\n }\n return true;\n};\n```\n---\n# Approach 3\n### Intuition\n\nThe key insight is the realization that we can compress all the necessary information about our lemonade stand\'s state into a single integer. By using the binary nature of computer memory, we can efficiently pack two separate counters into one variable, allowing for rapid updates and checks.\n\n\nThe intuition here is that by using bitwise operations, we can perform multiple actions in a single operation, potentially speeding up our solution. Additionally, by keeping all our state in a single variable, we\'re optimizing for cache performance, which can lead to significant speed improvements on modern hardware.\n\n### Approach\n\nOur approach can be broken down into several key steps:\n\n1. **State Initialization:** We start with a single integer variable initialized to 0. This will store our entire lemonade stand state.\n\n2. **Processing Transactions:** We iterate through each bill in the input array, updating our state based on the bill\'s value:\n\n - For a Dollar 5 bill, we increment the lower 16 bits of our state.\n - For a Dollar 10 bill, we first check if we have a Dollar 5 to give as change. If not, we return false. Otherwise, we decrement the Dollar 5 count and increment the Dollar 10 count.\n - For a Dollar 20 bill, we first try to give change using a Dollar 10 and a Dollar 5. If that\'s not possible, we try using three Dollar 5 bills. If neither option is possible, we return false.\n\n3. **State Updates:** We use bitwise operations to efficiently update our state:\n - Adding to the Dollar 5 count is a simple increment.\n - Adding to the Dollar 10 count involves adding 0x10000 to our state.\n - Removing bills involves subtracting from our state.\n\n4. **State Checks:** We use bitwise AND operations to check our bill counts:\n - AND with 0xFFFF checks the Dollar 5 count.\n - AND with 0xFFFF0000 checks the Dollar 10 count.\n\n5. **Final Result:** If we successfully process all transactions, we return true. Otherwise, we return false at the point where we can\'t make change.\n\nThis approach allows us to handle all transactions efficiently, using minimal memory and leveraging fast bitwise operations.\n\n### Complexity\n\n- **Time complexity: O(n)**, where n is the number of bills in the input array. We process each bill exactly once, and each processing step takes constant time (bitwise operations are typically O(1) on modern hardware).\n\n- **Space complexity: O(1)**. We use only a single integer variable to store our state, regardless of the input size. This constant space usage is one of the major advantages of this approach.\n\n\n\n# Code\n```Java []\nclass Solution {\n public boolean lemonadeChange(int[] bills) {\n int state = 0;\n \n for (int bill : bills) {\n if (bill == 5) {\n state++;\n } else if (bill == 10) {\n if ((state & 0xFFFF) == 0) return false;\n state--;\n state += 0x10000;\n } else { // bill == 20\n if ((state & 0xFFFF0000) != 0 && (state & 0xFFFF) != 0) {\n state -= 0x10001;\n } else if ((state & 0xFFFF) >= 3) {\n state -= 3;\n } else {\n return false;\n }\n }\n }\n \n return true;\n }\n}\n\n```\n```C++ []\nclass Solution {\npublic:\n bool lemonadeChange(vector<int>& bills) {\n int state = 0;\n \n for (int bill : bills) {\n if (bill == 5) {\n state++;\n } else if (bill == 10) {\n if (!(state & 0xFFFF)) return false;\n state--;\n state += 0x10000;\n } else { // bill == 20\n if ((state & 0xFFFF0000) && (state & 0xFFFF)) {\n state -= 0x10001;\n } else if ((state & 0xFFFF) >= 3) {\n state -= 3;\n } else {\n return false;\n }\n }\n }\n \n return true;\n }\n};\n\n```\n```Python []\nclass Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n state = 0 \n \n for bill in bills:\n if bill == 5:\n state += 1 \n elif bill == 10:\n if not (state & 0xFFFF): \n return False\n state -= 1 \n state += 0x10000 \n else: \n if (state & 0xFFFF0000) and (state & 0xFFFF): \n state -= 0x10001 \n elif (state & 0xFFFF) >= 3: $5\n state -= 3\n else:\n return False\n \n return True\n\n```\n```Go []\nfunc lemonadeChange(bills []int) bool {\n state := 0\n \n for _, bill := range bills {\n if bill == 5 {\n state++\n } else if bill == 10 {\n if state & 0xFFFF == 0 {\n return false\n }\n state--\n state += 0x10000\n } else { // bill == 20\n if state & 0xFFFF0000 != 0 && state & 0xFFFF != 0 {\n state -= 0x10001\n } else if state & 0xFFFF >= 3 {\n state -= 3\n } else {\n return false\n }\n }\n }\n \n return true\n}\n\n```\n```JavaScript []\n/**\n * @param {number[]} bills\n * @return {boolean}\n */\nvar lemonadeChange = function(bills) {\n let state = 0;\n \n for (let bill of bills) {\n if (bill === 5) {\n state++;\n } else if (bill === 10) {\n if (!(state & 0xFFFF)) return false;\n state--;\n state += 0x10000;\n } else { // bill === 20\n if ((state & 0xFFFF0000) && (state & 0xFFFF)) {\n state -= 0x10001;\n } else if ((state & 0xFFFF) >= 3) {\n state -= 3;\n } else {\n return false;\n }\n }\n }\n \n return true;\n};\n```\n---\n
| 11 | 1 |
['Array', 'Stack', 'Greedy', 'Bit Manipulation', 'C++', 'Java', 'Go', 'Python3', 'Rust', 'JavaScript']
| 1 |
lemonade-change
|
Java Intuitive with Explanation O(N) beats 100%.
|
java-intuitive-with-explanation-on-beats-n1rg
|
Firstly if an entry is not $5 then we can return false. Next greedy technique would be to return the change with maximum value. \nHence, suppose we have 3 x $5
|
h0me
|
NORMAL
|
2019-05-29T02:04:43.980341+00:00
|
2019-05-29T02:04:43.980384+00:00
| 1,851 | false |
Firstly if an entry is not $5 then we can return false. Next greedy technique would be to return the change with maximum value. \nHence, suppose we have 3 x $5 and 1 x $10, for an entry of $20 -> We would give a $10 and $5 instead of 3 x $5, which will increase the chance of more sale after 20. \n\n```\nclass Solution {\n public boolean lemonadeChange(int[] bills) {\n int fives = 0, tens = 0; \n if (bills.length < 1) return true;\n if (bills[0] != 5) return false;\n for (int index = 0; index < bills.length; ++index) {\n if (bills[index] == 5) \n fives++;\n else if (bills[index] == 10) {\n if (fives < 1)\n return false;\n fives--;\n tens++;\n } else {\n if (tens > 0 && fives > 0) {\n tens--;\n fives--;\n } else if (fives > 2) \n fives -= 3;\n else return false;\n }\n }\n return true;\n }\n}\n```\n\nIf you liked the post please upvote. Any suggestions are always welcome.
| 11 | 4 |
['Java']
| 1 |
lemonade-change
|
Javascript short & simple & readable
|
javascript-short-simple-readable-by-happ-5nej
|
javascript\n/**\n * 860. Lemonade Change\n * https://leetcode.com/problems/lemonade-change/\n * @param {number[]} bills\n * @return {boolean}\n */\nconst lemona
|
happywind
|
NORMAL
|
2020-03-01T05:21:56.472248+00:00
|
2020-03-01T05:21:56.472283+00:00
| 482 | false |
```javascript\n/**\n * 860. Lemonade Change\n * https://leetcode.com/problems/lemonade-change/\n * @param {number[]} bills\n * @return {boolean}\n */\nconst lemonadeChange = (bills) => {\n let fiveNum = 0, tenNum = 0\n for(let i = 0; i < bills.length; i++) {\n if (bills[i] === 5) { fiveNum++; continue }\n if (bills[i] === 10) { fiveNum--; tenNum++ }\n if (bills[i] === 20) { tenNum ? (tenNum--, fiveNum--) : fiveNum -= 3 }\n if (fiveNum < 0) return false\n }\n return true\n};\n\n\n```
| 10 | 0 |
[]
| 0 |
lemonade-change
|
EASY C++||O(N) time O(1) Space
|
easy-con-time-o1-space-by-garv_virmani-eb1v
|
Intuition\n Describe your first thoughts on how to solve this problem. \ncount 5 and 10 dollars bill\n# Approach\n Describe your approach to solving the problem
|
Garv_Virmani
|
NORMAL
|
2024-08-15T08:54:12.601005+00:00
|
2024-08-15T09:08:09.681813+00:00
| 1,602 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\ncount 5 and 10 dollars bill\n# Approach\n<!-- Describe your approach to solving the problem. -->\nif(bill==5) c5++\nif(bill==10) and c5>0 c5--\nif(bill==20){\n //Two choices\n //1. 10 + 5\n //2. 5 + 5 + 5\n}\nImportant Note:\nWe will prefer to give 10+5 instead of 5+5+5 because we gonna save 5 dollar for future 10 dollar bill customer\n\nexample:\n5|5|5|5|10|20|10\n\nif we give 5+5+5 to 20 then our answer will be wrong because we will left with 10 \n\nbut if we give 10+5 then we will have 5+5\n\nI hope you understood !!\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(1)\n# Code\n```\nclass Solution {\npublic:\n bool lemonadeChange(vector<int>& bills) {\n int c5 = 0, c10 = 0;\n for (auto bill : bills) {\n if (bill == 5)\n c5++;\n else if (bill == 10 && c5 >= 1) {\n c10++;\n c5--;\n } else if (bill == 20 && c10 >= 1 && c5 >= 1) {\n c10--;\n c5--;\n } else if (bill == 20 && c5 >= 3) {\n c5 -= 3;\n } else\n return false;\n }\n return true;\n }\n};\n```
| 8 | 0 |
['C++']
| 0 |
lemonade-change
|
Clear Python 3 solution faster than 90%
|
clear-python-3-solution-faster-than-90-b-l1gh
|
\nclass Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n count5, count10 = 0, 0\n for i in range(len(bills)):\n if
|
swap24
|
NORMAL
|
2020-08-24T14:57:33.700509+00:00
|
2020-08-24T14:57:33.700552+00:00
| 1,969 | false |
```\nclass Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n count5, count10 = 0, 0\n for i in range(len(bills)):\n if bills[i] == 5:\n count5 += 1\n elif bills[i] == 10:\n count10 += 1\n if not count5:\n return False\n count5 -= 1\n else:\n if count10 and count5:\n count10 -= 1\n count5 -= 1\n elif count5 > 2:\n count5 -= 3\n else:\n return False\n return True\n```
| 8 | 0 |
['Greedy', 'Python', 'Python3']
| 2 |
lemonade-change
|
Simple | Easy | O(n) | C++ | if-else only
|
simple-easy-on-c-if-else-only-by-gavnish-k2cr
|
\n# Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(1)\n Add your space complexity here, e.g. O(n) \n\n
|
gavnish_kumar
|
NORMAL
|
2024-08-15T04:55:27.680020+00:00
|
2024-08-15T04:55:27.680055+00:00
| 2,561 | false |
\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool lemonadeChange(vector<int>& bills) {\n int a=0,b=0,c=0;\n for(auto it: bills){\n if(it==5) a++;\n else if(it==10){\n b++;\n if(a==0) return false;\n else a--;\n }\n else {\n if(b!=0 && a>0){\n b--;\n a--;\n }\n else if(b==0 && a>=3){\n a-=3;\n }\n else{\n return false;\n }\n c++;\n }\n }\n return true;\n }\n};\n```
| 7 | 0 |
['C++']
| 6 |
lemonade-change
|
🚀 Explained Greedy Basic Solution || Easy ♻️|| Concise 🎗️|| 4 Langauge
|
explained-greedy-basic-solution-easy-con-qiw1
|
Screenshot \uD83C\uDF89\n\n\n\n---\n\n# Intuition \uD83E\uDD14\n\n Given Imforamtion -->\n\n We have a array of bills consider as store of cash notes\n\n
|
Prakhar-002
|
NORMAL
|
2024-05-30T10:30:14.593298+00:00
|
2024-05-30T10:30:14.593323+00:00
| 1,859 | false |
# Screenshot \uD83C\uDF89\n\n\n\n---\n\n# Intuition \uD83E\uDD14\n\n Given Imforamtion -->\n\n We have a array of bills consider as store of cash notes\n\n \n`Bills all Ith pos assign a customer who bring us bills[i] cash`\n\n1. `From each customer` we have to `take exactly 5 doller` \n\n2. `At start` We don\'t have any cash in hand `0 Doller in hand`\n\n---\n\n# Approach \uD83E\uDEE0\n\n As we know rather we get customer with \n\n 5 Doller -> Take it as it is\n\n 10 Doller -> return 1 -- 5 Doller bill\n\n 20 Doller -> return 1 -- 5 Doller and 1 -- 10 Doller bill\n\n 20 Doller -> or return 3 -- 5 Doller bills\n\n---\n\n# Understand with code \uD83E\uDD70\n\n There will be 6 steps \n\n Step 1 -> Make variables five and ten\n\n Step 2 -> Interate whole loop \n\n Step 3 -> check Ith customer bill \n\n if bill = 5 -> Then add in five\n\n Step 4 -> If bill = 10 \n\n Check 5 if >= 1 then dec five by 1 and inc ten by 1\n\n else return false\n\n Step 5 -> If bill = 20 \n\n Check 5 if >= 1 And 10 >= 1 \n then dec five by 1 and ten by 1\n\n Check 5 elseif >= 3 \n then dec five by 3\n\n Else return false\n \n\n Step 6 -> return true\n---\n\n\n\n# Complexity \u2603\uFE0F\n- Time complexity: $$O(n)$$ \u267B\uFE0F\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$ \uD83D\uDE80\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n---\n\n# Code \u2728\n\n\n``` JAVA []\nclass Solution {\n public boolean lemonadeChange(int[] bills) {\n int five = 0;\n int ten = 0;\n\n for(int bill : bills){\n // if we get 5$ \n if (bill == 5) {\n five++;\n } else if (bill == 10) { // If we get 10$ \n if (five >= 1) { // we have to return 5$ so we should have it first\n five--;\n ten++;\n } else {\n return false;\n }\n } else { // If we get 20$ \n if (five >= 1 && ten >= 1) { // We have to return 15$ so 1 -- 10$ and 1 -- 5$\n ten--;\n five--;\n } else if (five >= 3) { // OR we can return 3 -- 5% \n five -= 3;\n } else {\n return false;\n }\n }\n }\n\n return true;\n }\n}\n```\n```JAVASCRIPT []\nvar lemonadeChange = function (bills) {\n let five = 0;\n let ten = 0;\n\n for (const bill of bills) {\n // if we get 5$ \n if (bill == 5) {\n five++;\n } else if (bill == 10) { // If we get 10$ \n if (five >= 1) { // we have to return 5$ so we should have it first\n five--;\n ten++;\n } else {\n return false;\n }\n } else { // If we get 20$ \n if (five >= 1 && ten >= 1) { // We have to return 15$ so 1 -- 10$ and 1 -- 5$\n ten--;\n five--;\n } else if (five >= 3) { // OR we can return 3-- 5% \n five -= 3;\n } else {\n return false;\n }\n }\n }\n\n return true;\n};\n```\n```PYTHON []\nclass Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n five = 0\n ten = 0\n\n for bill in bills:\n # if we get 5$\n if bill == 5:\n five += 1\n\n elif bill == 10:\n if five >= 1:\n five -= 1\n ten += 1\n\n else:\n return False\n\n else:\n if five >= 1 and ten >= 1:\n five -= 1\n ten -= 1\n\n elif five >= 3:\n five -= 3\n\n else:\n return False\n\n return True\n\n```\n```c []\nbool lemonadeChange(int* bills, int billsSize) {\n int five = 0;\n int ten = 0;\n\n for (int i = 0; i < billsSize; i++) {\n // if we get 5$\n if (bills[i] == 5) {\n five++;\n } else if (bills[i] == 10) { // If we get 10$\n if (five >= 1) { // we have to return 5$ so we should have it first\n five--;\n ten++;\n } else {\n return false;\n }\n } else { // If we get 20$\n if (five >= 1 &&\n ten >= 1) { // We have to return 15$ so 1 -- 10$ and 1 -- 5$\n ten--;\n five--;\n } else if (five >= 3) { // OR we can return 3-- 5%\n five -= 3;\n } else {\n return false;\n }\n }\n }\n\n return true;\n}\n```\n
| 7 | 0 |
['Array', 'Greedy', 'C', 'Java', 'Python3', 'JavaScript']
| 2 |
lemonade-change
|
Easy C++ Solution with Video Explanations
|
easy-c-solution-with-video-explanations-7atc2
|
Video Explanation\nhttps://youtu.be/pqM-asL-4rs\n\n# Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem involves handling a se
|
prajaktakap00r
|
NORMAL
|
2024-08-15T00:57:50.114399+00:00
|
2024-08-15T01:15:15.505266+00:00
| 864 | false |
# Video Explanation\nhttps://youtu.be/pqM-asL-4rs\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem involves handling a sequence of payments with `$5`, `$10`, and `$20` bills, while giving change for each payment according to the customers bill. We must ensure that we always have enough change in hand to return to the customer. The main challenge lies in effectively managing `$5 `and `$10` bills to ensure we can cover the cost of higher denomination payments (`$10` or`$20`).\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialize Variables: We need two counters, five and ten, to track the number of `$5` and `$10` bills we currently have.\n2. Iterate through the bills:\n- For each `$5` bill, we simply increment the five counter, as no change is required.\n- For each `$10` bill, we decrement the five counter (if we have any) because we need to give back `$5` as change and then increment the ten counter.\n- For each `$20` bill, we try to give change using one `$10` bill and one `$5` bill first (as this preserves more `$5` bills). \n- If that isn\'t possible, we check if we can give change using three `$5` bills instead. \n- If neither option works, the transaction fails, and we return false.\n3. Final Check: If we successfully process all the bills, return true.\n\n# Complexity\n- Time complexity:$$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool lemonadeChange(vector<int>& bills) {\n int five=0;\n int ten=0;\n for(int i=0;i<bills.size();i++){\n if(bills[i]==5){five++;}\n else if(bills[i]==10){\n if(five==0)return false;\n five--;\n ten++;\n }else{\n if(ten>0 && five>0){\n ten--;\n five--;\n }else if(five>=3){\n five-=3;\n }else{\n return false;\n }\n }\n }\n return true;\n }\n};\n```
| 6 | 1 |
['C++']
| 2 |
lemonade-change
|
Java. LemonadeChange
|
java-lemonadechange-by-red_planet-okux
|
\n\nclass Solution {\n public boolean lemonadeChange(int[] bills) {\n int five = 0;\n int ten = 0;\n for (int bill : bills)\n {\n
|
red_planet
|
NORMAL
|
2023-05-16T11:31:32.729464+00:00
|
2023-05-16T11:31:32.729502+00:00
| 1,595 | false |
\n```\nclass Solution {\n public boolean lemonadeChange(int[] bills) {\n int five = 0;\n int ten = 0;\n for (int bill : bills)\n {\n if (bill == 5) five++;\n else if (bill == 10 && five > 0) {\n ten++;\n five--;\n }\n else if (bill == 20)\n {\n if (ten > 0)\n {\n if (five > 0)\n {\n ten--;\n five--;\n }\n else return false;\n }\n else if (five > 2) five -= 3;\n else return false;\n }\n else return false;\n }\n return true;\n }\n}\n```
| 6 | 0 |
['Java']
| 0 |
lemonade-change
|
✅💯🔥Simple Code📌🚀| 🔥✔️Easy to understand🎯 | 🎓🧠Beginner friendly🔥| O(n) Time Complexity💀💯
|
simple-code-easy-to-understand-beginner-qtdzv
|
Solution tuntun mosi ki photo ke baad hai. Scroll Down\n\n# Code\njava []\nclass Solution {\n public boolean lemonadeChange(int[] bills) {\n int curr1
|
atishayj4in
|
NORMAL
|
2024-08-20T21:03:19.545748+00:00
|
2024-08-20T21:03:19.545781+00:00
| 139 | false |
Solution tuntun mosi ki photo ke baad hai. Scroll Down\n\n# Code\n```java []\nclass Solution {\n public boolean lemonadeChange(int[] bills) {\n int curr10=0;\n int curr5=0;\n for(int i=0; i<bills.length; i++){\n if(bills[i]==5){\n curr5++;\n }else if(bills[i]==10){\n curr10++;\n if(curr5!=0){\n curr5--;\n }else{\n return false;\n }\n } else{\n if(curr5>0){\n if(curr10>0){\n curr5--;\n curr10--;\n }else{\n if(curr5>=3){\n curr5-=3;\n }else{\n return false;\n }\n }\n }else{\n return false;\n }\n }\n }\n return true;\n }\n}\n```\n
| 5 | 0 |
['Array', 'Greedy', 'C', 'Python', 'C++', 'Java', 'JavaScript']
| 0 |
lemonade-change
|
Beats 100%EASY C++ CODE
|
beats-100easy-c-code-by-pradeepredt-dm9u
|
Intuition\n Describe your first thoughts on how to solve this problem. \nGREEDY APPROACH\n# Approach\n Describe your approach to solving the problem. \n1. Initi
|
pradeepredt
|
NORMAL
|
2024-08-15T06:00:30.216399+00:00
|
2024-08-15T06:03:51.067991+00:00
| 967 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nGREEDY APPROACH\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialization: The function uses two counters: f for the number of 5 bills and t for the number of 10 bills.\n\n2. Decision Points:\n\n ->For a 10 bill, ensure you have a 5 bill to give as change.\n ->For a 20 bill, prioritize using one 10 bill and one 5 bill for change if available; otherwise, use three 5 bills.\n\n3. Processing Bills:\n\n ->5 Bill : Increment the 5 bill counter (f).\n ->10 Bill: Increment the 10 bill counter (t) and check if there is at least one 5 bill to provide change. If not, return false.\n ->20 Bill: Try to provide change using one 10 bill and one 5 bill. If that\'s not possible, check if there are at least three 5 bills. If neither option is available, return false.\n\n4. Final Result:\n If the function manages to provide the correct change for all transactions, it returns true; otherwise, it returns false.\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool lemonadeChange(vector<int>& bills) {\n int f=0,t=0;\n int n=bills.size();\n for(int i=0;i<n;i++)\n {\n if(bills[i]==5)f++;\n else if(bills[i]==10)\n {\n t++;\n if(f>0)\n {\n f--;\n continue;\n }\n return false;\n }\n else\n {\n if(f>0&&t>0)\n {\n f--,t--;\n continue;\n }\n else if(f>=3)\n {\n f-=3;\n continue;\n }\n return false;\n }\n }\n return true;\n }\n};\n\n```\n\n
| 5 | 0 |
['Array', 'Greedy', 'C++']
| 2 |
lemonade-change
|
DCC-15 AUGUST 2024|| GREEDY
|
dcc-15-august-2024-greedy-by-sajaltiwari-mb7l
|
Problem Understanding and Intuition:\n\nThe problem "Lemonade Change" is about a lemonade stand where each lemonade costs $5. The customers pay with $5, $10, or
|
sajaltiwari007
|
NORMAL
|
2024-08-15T04:03:58.212622+00:00
|
2024-08-15T07:05:52.409978+00:00
| 1,865 | false |
### Problem Understanding and Intuition:\n\nThe problem "Lemonade Change" is about a lemonade stand where each lemonade costs $5. The customers pay with $5, $10, or $20 bills. The goal is to determine whether the seller can provide the correct change to each customer in the order they arrive.\n\n### Approach:\n\n1. **Tracking Bills:**\n - We need to keep track of the number of $5, $10, and $20 bills we have since we need these to give back the correct change.\n - We use three variables: `five`, `ten`, and `twenty` to count the number of $5, $10, and $20 bills, respectively.\n\n2. **Processing Each Bill:**\n - If the customer pays with a $5 bill, no change is needed, so we simply increase the count of `five`.\n - If the customer pays with a $10 bill, we need to give back $5 in change. We check if we have at least one $5 bill:\n - If yes, we decrease the `five` count and increase the `ten` count.\n - If no, we return `false` because we cannot provide the correct change.\n - If the customer pays with a $20 bill, we need to give back $15 in change. The optimal way to do this is:\n - First, try to use one $10 bill and one $5 bill.\n - If we don\'t have a $10 bill, we must use three $5 bills.\n - If neither option is available, we return `false` because we cannot provide the correct change.\n\n3. **Complexity Consideration:**\n - The approach involves iterating through each bill in the array and making constant-time operations (checking and updating the counts).\n - **Time Complexity:** `O(n)`, where `n` is the length of the `bills` array.\n - **Space Complexity:** `O(1)` since we\'re only using a fixed number of variables to store the counts of the bills.\n\n# Code\n```\nclass Solution {\n public boolean lemonadeChange(int[] bills) {\n int five = 0;\n int ten =0;\n <!-- int twenty = 0; -->\n int coins=0;\n for(int i=0;i<bills.length;i++){\n if(bills[i]==5) five++;\n if(bills[i]==10) ten++;\n <!-- if(bills[i]==20) twenty++; -->\n int change = bills[i]-5;\n if(change==0) continue;\n <!-- while(change>=20 && twenty>0){\n change-=20;\n twenty--;\n } -->\n while(change>=10 && ten>0){\n change-=10;\n ten--;\n }\n while(change>=5 && five>0){\n change-=5;\n five--;\n }\n if(change!=0) return false;\n }\n return true;\n }\n}\n```
| 5 | 0 |
['Greedy', 'Java']
| 2 |
lemonade-change
|
simple and easy Python solution 😍❤️🔥
|
simple-and-easy-python-solution-by-shish-nju1
|
\n# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n###### Let\'s Connect on LinkedIn: www.linkedin.com/in/shishirrsiam\n###### Let\'s Connect on Facebook
|
shishirRsiam
|
NORMAL
|
2024-08-15T01:16:33.602323+00:00
|
2024-08-15T01:16:33.602351+00:00
| 1,367 | false |
\n# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n###### Let\'s Connect on LinkedIn: www.linkedin.com/in/shishirrsiam\n###### Let\'s Connect on Facebook: www.fb.com/shishirrsiam\n\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1), Constant\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution(object):\n def lemonadeChange(self, bills):\n count = {5: 0, 10: 0}\n for bill in bills:\n if bill == 5:\n count[5] += 1\n elif bill == 10:\n if count[5]:\n count[5] -= 1\n count[10] += 1\n else: return False\n else:\n if count[5] and count[10]:\n count[5] -= 1\n count[10] -= 1\n elif count[5] >= 3:\n count[5] -= 3\n else: return False\n return True\n```
| 5 | 0 |
['Array', 'Greedy', 'Counting', 'Python', 'Python3']
| 3 |
lemonade-change
|
Javascript solution using map - lemonadeChange
|
javascript-solution-using-map-lemonadech-a8yj
|
\nvar lemonadeChange = function(bills) {\n let change={\'5\':0, \'10\':0};\n for (let bill of bills) {\n if (bill==5) change[5]++;\n else if
|
natan7366
|
NORMAL
|
2020-11-24T11:36:55.645262+00:00
|
2020-11-24T11:39:20.521812+00:00
| 435 | false |
```\nvar lemonadeChange = function(bills) {\n let change={\'5\':0, \'10\':0};\n for (let bill of bills) {\n if (bill==5) change[5]++;\n else if (bill==10) {\n if (!change[5]) return false\n change[10]++;\n change[5]--;\n } else { //bill==20\n if (change[5] && change[10]) { \n\t\t\t// first way for giving change: bill of 10 + bill of 5\n change[10]--;\n change[5]--;\n }else if(change[5]>=3) {\n\t\t\t// second way for giving change: 3 bills of 5\n change[5] -= 3 ;\n }else return false\n }\n }\n return true\n};\n```
| 5 | 0 |
['JavaScript']
| 0 |
lemonade-change
|
java easy undersand
|
java-easy-undersand-by-iamwds-vlq4
|
\nclass Solution {\n public boolean lemonadeChange(int[] bills) {\n int count5 = 0;\n int count10 = 0;\n for(int b : bills){\n
|
iamwds
|
NORMAL
|
2018-07-01T03:09:31.047910+00:00
|
2018-07-01T03:09:31.047910+00:00
| 2,080 | false |
```\nclass Solution {\n public boolean lemonadeChange(int[] bills) {\n int count5 = 0;\n int count10 = 0;\n for(int b : bills){\n if(b == 5){\n count5++;\n }else if(b == 10){\n if(count5 == 0){\n return false;\n }else{\n count5--;\n count10++;\n }\n }else{\n if(count10 > 0 && count5 > 0){\n count5--;\n count10--;\n continue;\n }else if(count5 >= 3){\n count5 -= 3;\n continue;\n }else{\n return false;\n }\n }\n }\n return true;\n }\n}\n```
| 5 | 0 |
[]
| 1 |
lemonade-change
|
The shortest C# solution
|
the-shortest-c-solution-by-gregzhadko-u399
|
Intuition\nWe need to keep track of how many fives and tens we have so that we can give change for different bills. If at any time we don\'t have the necessary
|
gregzhadko
|
NORMAL
|
2024-08-15T12:35:38.782229+00:00
|
2024-08-15T12:35:38.782269+00:00
| 425 | false |
# Intuition\nWe need to keep track of how many fives and tens we have so that we can give change for different bills. If at any time we don\'t have the necessary bills to give change, we should return `false`.\n\n# Approach\nWe use two variables, `numberOf5` and `numberOf10`, to keep track of the number of 5s and 10s respectively. Initially, we set both of these variables to 0.\n\nThen, we go through the "bills" array and check each bill as follows:\n\n* If `bill[i] == 5`, we increment the `numberOf5` counter.\n* If `bill[i] == 10`, we decrement `numberOf5` and increment `numberOf10`\n* If `bill[i] == 20`, we check if there are still any 10-dollars, if so we decrement `numberOf10` and `numberOf5` otherwise decrease `numberOf5` by three. \n\nAt the end of this process, we check if `numberOf5` and `numberOf10` are negative then it is impossible to provide a change.\n\nTo avoid using many ifs I used tuples and a switch expression.\n\n# Complexity\n- Time complexity:\nO(n). We iterate over the array once.\n\n- Space complexity:\nO(1) because we are using only two \n\n# Code\n\n## C# \n```c#\npublic class Solution {\n public bool LemonadeChange(int[] bills) {\n var (numberOf5, numberOf10) = (0, 0);\n foreach(var bill in bills) {\n (numberOf5, numberOf10) = bill switch {\n 5 => (numberOf5 + 1, numberOf10),\n 10 => (numberOf5 - 1, numberOf10 + 1),\n 20 when numberOf10 == 0 => (numberOf5 - 3, 0),\n _ => (numberOf5 - 1, numberOf10 - 1)\n };\n\n if (numberOf5 < 0 || numberOf10 < 0) {\n return false;\n }\n }\n\n return true;\n }\n}\n```
| 4 | 0 |
['C#']
| 2 |
lemonade-change
|
Easy 7 line Java Solution || Beats 100% || Easier Than Easy
|
easy-7-line-java-solution-beats-100-easi-yo4o
|
\n\n\n# Code\nJava []\nclass Solution {\n public boolean lemonadeChange(int[] bills){\n int five=0, tens=0;\n for(int bill:bills){\n if(bi
|
himanshu0805
|
NORMAL
|
2024-08-15T07:36:08.795755+00:00
|
2024-08-15T07:36:08.795791+00:00
| 305 | false |
\n\n\n# Code\n``` Java []\nclass Solution {\n public boolean lemonadeChange(int[] bills){\n int five=0, tens=0;\n for(int bill:bills){\n if(bill==5){\n five++;\n }else if(bill ==10 ){\n if(five==0) return false;\n tens++;\n five--;\n }\n else if(bill==20){\n if(five>0 && tens>0)\n {\n tens--;\n five--;\n }\n else if(five>2){\n five-=3;\n }\n else{\n return false;\n }\n }\n }\n \n \n return true;\n}}\n```
| 4 | 0 |
['Array', 'Greedy', 'Java']
| 0 |
lemonade-change
|
🔥Explanations No One Will Give You🎓🧠Very Detailed Approach🎯🔥Extremely Simple And Effective🔥
|
explanations-no-one-will-give-youvery-de-on3p
|
Complexity\n- Time complexity:\nO{n}\n\n- Space complexity:\nO{1}\n\n# Code\n\nclass Solution {\npublic:\n bool lemonadeChange(vector<int>& bills) {\n
|
ShivanshGoel1611
|
NORMAL
|
2024-08-15T05:02:06.911427+00:00
|
2024-08-15T05:02:06.911463+00:00
| 558 | false |
# Complexity\n- Time complexity:\nO{n}\n\n- Space complexity:\nO{1}\n\n# Code\n```\nclass Solution {\npublic:\n bool lemonadeChange(vector<int>& bills) {\n int n = bills.size();\n int a = 0;\n int b = 0;\n int c = 0;\n for (int i = 0; i < n; i++) {\n if (bills[i] == 5) {\n a++; // 8\n }\n if (bills[i] == 10) {\n b++; // 1\n if (a > 0) {\n a--;\n }\n else\n {\n return false;\n }\n }\n if (bills[i] == 20) {\n c++;\n if (a <= 0) {\n return false;\n }\n\n if (b <= 0) {\n if (a >= 3) {\n a=a-3;\n }\n else\n {\n return false;\n }\n }\n if(b>0)\n {\n a--;\n b--;\n }\n }\n }\n\n return true;\n }\n};\n```
| 4 | 1 |
['Array', 'Greedy', 'Python', 'C++', 'Java']
| 3 |
lemonade-change
|
Greedily spend 5 dollar change | Java | C++
|
greedily-spend-5-dollar-change-java-c-by-q086
|
Intuition, approach, and complexity dicussed in video solution in detail\nhttps://youtu.be/p_jI8P-AKP8\n# Code\nJava\n\nclass Solution {\n public boolean lem
|
Lazy_Potato_
|
NORMAL
|
2024-08-15T05:00:02.412803+00:00
|
2024-08-15T05:00:02.412855+00:00
| 362 | false |
# Intuition, approach, and complexity dicussed in video solution in detail\nhttps://youtu.be/p_jI8P-AKP8\n# Code\nJava\n```\nclass Solution {\n public boolean lemonadeChange(int[] bills) {\n int fiveCnt = 0, tenCnt = 0;\n for(var bill : bills){\n if(bill == 5)fiveCnt++;\n else if(bill == 10){\n if(fiveCnt == 0)return false;\n else fiveCnt--;\n tenCnt++;\n }else{\n if(fiveCnt == 0 || (fiveCnt < 3 && tenCnt == 0))return false;\n else{\n if(tenCnt == 0)fiveCnt -= 3;\n else{\n fiveCnt--;\n tenCnt--;\n }\n }\n }\n \n }\n return true;\n }\n}\n```\nC++\n```\nclass Solution {\npublic:\n bool lemonadeChange(vector<int>& bills) {\n int fiveCnt = 0, tenCnt = 0;\n for(auto bill : bills){\n if(bill == 5)fiveCnt++;\n else if(bill == 10){\n if(fiveCnt == 0)return false;\n else fiveCnt--;\n tenCnt++;\n }else{\n if(fiveCnt == 0 || (fiveCnt < 3 && tenCnt == 0))return false;\n else{\n if(tenCnt == 0)fiveCnt -= 3;\n else{\n fiveCnt--;\n tenCnt--;\n }\n }\n }\n \n }\n return true;\n }\n};\n```
| 4 | 0 |
['Array', 'Greedy', 'C++', 'Java']
| 1 |
lemonade-change
|
Python3 Solution
|
python3-solution-by-motaharozzaman1996-l8oc
|
\n\nclass Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n five=ten=0\n for bill in bills:\n if bill==5:\n
|
Motaharozzaman1996
|
NORMAL
|
2024-08-15T02:17:56.184790+00:00
|
2024-08-15T02:17:56.184824+00:00
| 712 | false |
\n```\nclass Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n five=ten=0\n for bill in bills:\n if bill==5:\n five+=1\n elif bill==10:\n five,ten=five-1,ten+1\n elif ten>0:\n five,ten=five-1,ten-1\n else:\n five-=3\n if five<0:\n return False\n return True \n```
| 4 | 0 |
['Python', 'Python3']
| 1 |
lemonade-change
|
C++ | Efficient Solution for "Lemonade Change" | 55ms Beats 97.21% | Python | Java
|
c-efficient-solution-for-lemonade-change-htno
|
---\n\n# Intuition\nTo determine if we can provide the correct change to every customer at a lemonade stand, we need to track the number of $5 and $10 bills we
|
user4612MW
|
NORMAL
|
2024-08-15T01:09:24.144534+00:00
|
2024-08-15T02:56:50.134677+00:00
| 29 | false |
---\n\n# Intuition\nTo determine if we can provide the correct change to every customer at a lemonade stand, we need to track the number of `$`5 and `$`10 bills we have as we process each customer\u2019s payment. The challenge is to make sure we always have enough `$`5 and `$`10 bills to give the correct change for a `$`10 or `$`20 bill, respectively.\n\n# Approach\nWe iterate through each customer\'s payment, increasing our count of `$`5 bills if they pay with a `$`5 bill. For a `$`10 bill, we check if we have a `$`5 bill for change, if not, return false. With a `$`20 bill, we first try to give one `$`10 bill and one `$`5 bill as change. If that\'s not possible, we then attempt to give three `$`5 bills. If neither option is available, return false. This confirms we can provide the correct change to every customer if we finish processing without issues.\n\n# Complexity\n- **Time Complexity** $$O(n)$$, where $$n$$ is the length of the bills array. We only need a single pass through the array.\n- **Space Complexity** $$O(1)$$, as we only use a fixed amount of extra space for tracking the counts of `$`5 and `$`10 bills.\n\n# Code\n```cpp []\nclass Solution {\npublic:\n bool lemonadeChange(vector<int>& bills) {\n int five{0}, ten{0}, i{0};\n while (i < bills.size()) {\n if (bills[i] == 5) five++;\n else if (bills[i] == 10) { if (!five--) return false; ten++; }\n else if (ten && five--) ten--;\n else if (five >= 3) five -= 3; \n else return false;\n i++;\n }\n return true;\n }\n};\n```\n\n```java []\nclass Solution {\n public boolean lemonadeChange(int[] bills) {\n int five = 0, ten = 0, i = 0;\n while (i < bills.length) {\n if (bills[i] == 5) five++;\n else if (bills[i] == 10) { if (five-- <= 0) return false; ten++; }\n else if (ten > 0 && five-- > 0) ten--;\n else if (five >= 3) five -= 3; \n else return false;\n i++;\n }\n return true;\n }\n}\n```\n```python []\nclass Solution:\n def lemonadeChange(self, bills):\n five, ten, i = 0, 0, 0\n while i < len(bills):\n if bills[i] == 5:\n five += 1\n elif bills[i] == 10:\n if five <= 0:\n return False\n five -= 1\n ten += 1\n elif ten > 0 and five > 0:\n ten -= 1\n five -= 1\n elif five >= 3:\n five -= 3\n else:\n return False\n i += 1\n return True\n\n```\n**Happy Independence Day**\n\n---\n
| 4 | 0 |
['Greedy', 'Python', 'C++', 'Java']
| 0 |
lemonade-change
|
simple and easy C++ solution 😍❤️🔥
|
simple-and-easy-c-solution-by-shishirrsi-dfhd
|
\n# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n###### Let\'s Connect on LinkedIn: www.linkedin.com/in/shishirrsiam\n###### Let\'s Connect on Facebook
|
shishirRsiam
|
NORMAL
|
2024-08-15T01:05:59.770148+00:00
|
2024-08-15T01:05:59.770167+00:00
| 632 | false |
\n# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n###### Let\'s Connect on LinkedIn: www.linkedin.com/in/shishirrsiam\n###### Let\'s Connect on Facebook: www.fb.com/shishirrsiam\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1), Constant \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool lemonadeChange(vector<int>& bills) \n {\n vector<int>count(25);\n for(auto bill:bills)\n {\n if(bill == 5) count[5]++;\n else if(bill == 10) \n {\n if(count[5]) count[5]--;\n else return false;\n count[10]++;\n }\n else \n {\n if(count[5] and count[10]) count[5]--, count[10]--;\n else if(count[5] > 2) count[5] -= 3;\n else return false;\n }\n }\n return true;\n }\n};\n```
| 4 | 1 |
['Array', 'Greedy', 'Counting', 'C++']
| 3 |
lemonade-change
|
BEAT 98% USERS|| 4 step in depth solution.
|
beat-98-users-4-step-in-depth-solution-b-eryz
|
Intuition\n Describe your first thoughts on how to solve this problem. \nUSE SIMPLE GREEDY.\n\n# Approach\n Describe your approach to solving the problem. \nSte
|
Abhishekkant135
|
NORMAL
|
2024-04-12T13:02:25.732122+00:00
|
2024-04-12T13:05:10.231868+00:00
| 645 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUSE SIMPLE GREEDY.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n**Steps:**\n\n1. **Initializing Variables:**\n - `int five = 0`: Initializes a variable `five` to 0 to keep track of the number of $5 bills the stand has.\n - `int ten = 0`: Initializes a variable `ten` to 0 to keep track of the number of $10 bills the stand has.\n\n2. **Processing Bills:**\n - The `for` loop iterates through each bill (`bills[i]`) in the `bills` array.\n - **Handling $5 Bills:**\n - `if (bills[i] == 5)`: If the current bill is $5, the `five` counter is incremented.\n - **Handling $10 Bills:**\n - `else if (bills[i] == 10)`: If the current bill is $10, the code checks if there are enough $5 bills for change:\n - `five--`: Decrements the `five` counter as a $5 bill is used for change.\n - `ten++`: Increments the `ten` counter as a $10 bill is received.\n - **Handling $20 Bills:**\n - `else`: If the current bill is $20:\n - **Prioritizing $10 Bills (if available):**\n - `if (ten > 0)`: This checks if there\'s at least one $10 bill available.\n - `ten--`: Decrements the `ten` counter as a $10 bill is used for change.\n - `five--`: Decrements the `five` counter as a $5 bill is used for change (to make $15).\n - **Using Only $5 Bills (if no $10 bills):**\n - `else five = five - 3`: If there are no $10 bills, this subtracts 3 from `five`. This is a check to ensure the stand has enough $5 bills (at least 3) to provide change for a $20 bill.\n - **Checking for Negative Values:**\n - `if (ten < 0 || five < 0)`: After processing each bill, this condition checks if the `ten` or `five` counters become negative. A negative count signifies that the stand cannot provide sufficient change for previous transactions. In that case, the function returns `false`.\n\n3. **Returning the Result:**\n - After iterating through all bills, if no negative counts were encountered, the loop completes, and the function returns `true`, indicating the stand can provide change for all customers.\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe complexity in O(N).\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n- The code uses constant extra space for the `five` and `ten` variables, leading to a space complexity of O(1).\n# Code\n```\nclass Solution {\n public boolean lemonadeChange(int[] bills) {\n int five=0;\n int ten=0;\n for(int i=0;i<bills.length;i++){\n if(bills[i]==5){\n five++;\n }\n else if(bills[i]==10){\n five--;\n ten++;\n }\n else{\n if(ten>0){\n ten--;\n five--;\n }\n else five=five-3;\n \n }\n if(ten<0 || five<0){\n return false;\n }\n }\n return true;\n }\n}\n```
| 4 | 0 |
['Greedy', 'Java']
| 0 |
lemonade-change
|
greedy, try_fold
|
greedy-try_fold-by-user5285zn-1xlt
|
Code\n\nimpl Solution {\n pub fn lemonade_change(bills: Vec<i32>) -> bool {\n bills.into_iter().try_fold([0,0],|[a,b],x|\n match x {\n
|
user5285Zn
|
NORMAL
|
2023-12-27T13:25:33.399070+00:00
|
2023-12-27T13:25:33.399102+00:00
| 28 | false |
# Code\n```\nimpl Solution {\n pub fn lemonade_change(bills: Vec<i32>) -> bool {\n bills.into_iter().try_fold([0,0],|[a,b],x|\n match x {\n 5 => Some([a+1, b]),\n 10 if a > 0 => Some([a-1,b+1]),\n 20 if a > 0 && b > 0 => Some([a-1, b-1]),\n 20 if a > 2 && b == 0 => Some([a-3, b]),\n _ => None,\n }\n ).is_some()\n }\n}\n```
| 4 | 0 |
['Rust']
| 0 |
lemonade-change
|
Beats 100% of users with C++ || Using Map or Using Counting Approach || Best Solution ||
|
beats-100-of-users-with-c-using-map-or-u-7dw0
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\nif you like the approach please upvote it\n\n\n\n\n\n\nif you like the approach pleas
|
abhirajpratapsingh
|
NORMAL
|
2023-12-21T15:49:39.805755+00:00
|
2023-12-21T15:49:39.805834+00:00
| 251 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nif you like the approach please upvote it\n\n\n\n\n\n\nif you like the approach please upvote it\n\n\n\n\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThere Are two Approach that i use for solving this question \n1 :- Hash map ( ordered map )\n2 :- Using counting \n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->O( N )\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->O ( 1 )\n\n# Code\n```\nclass Solution {\npublic:\n bool lemonadeChange(vector<int>& bills) \n {\n map<int,int>mp;\n for(int i=0;i<bills.size();i++)\n {\n if(bills[i]==5)\n mp[5]++;\n else if(bills[i]==10)\n {\n mp[10]++;\n if(mp[5]>0)\n mp[5]--;\n else\n return false;\n }\n else if(bills[i]==20)\n {\n mp[20]++;\n if(mp[10]>0 && mp[5]>0)\n {\n mp[10]--;\n mp[5]--;\n }\n else if(mp[5]>2)\n {\n mp[5]=mp[5]-3;\n }\n else\n return false;\n }\n }\n return true;\n }\n};\n```\n#code\n```\nclass Solution {\npublic:\n bool lemonadeChange(vector<int>& bills) \n {\n int five = 0, ten = 0;\n for (int i = 0; i < bills.size(); i++)\n {\n if (bills[i] == 5)\n five++;\n else if (bills[i] == 10)\n {\n if (five > 0)\n {\n five--;\n ten++;\n }\n else\n return 0;\n } \n else\n {\n if (five > 0 && ten > 0) \n {\n five--;\n ten--;\n } \n else if (five >= 3) \n {\n five -= 3;\n }\n else\n return 0;\n }\n }\n return 1;\n }\n};
| 4 | 0 |
['Array', 'Hash Table', 'Greedy', 'Ordered Map', 'Counting', 'C++']
| 0 |
lemonade-change
|
✅EASIEST SOLUTION
|
easiest-solution-by-vishu_0123-a3xf
|
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
|
vishu_0123
|
NORMAL
|
2023-06-12T14:22:54.845971+00:00
|
2023-06-12T14:22:54.846014+00:00
| 1,122 | false |
# 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 {\npublic:\n bool lemonadeChange(vector<int>& bills) {\n int five=0,ten=0;\n for(int i=0;i<bills.size();i++){\n if(bills[i] ==5) five++;\n else if(bills[i] ==10){\n if(five>0){five--;ten++;}\n else return 0;\n }\n else {\n if(five>0 && ten>0){\n five--;ten--;\n }\n else if(five>=3){five-=3;}\n else return 0;\n }\n \n }\n return 1; \n }\n};\nDO UPVOTE\n```
| 4 | 0 |
['C++']
| 0 |
lemonade-change
|
Easy c++ solution Beats 96.84% in time
|
easy-c-solution-beats-9684-in-time-by-ag-3fwp
|
\n# Intuition\n Describe your first thoughts on how to solve this problem. \nwe just store count of 5,10,20 \n\n# Approach\n Describe your approach to solving t
|
ag893573
|
NORMAL
|
2023-01-09T14:47:54.507971+00:00
|
2023-01-09T14:47:54.508028+00:00
| 1,237 | false |
\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nwe just store count of 5,10,20 \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nusing arr[3] to store count of 5 ,10,20 \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)$$ -->\nusing array of size 3\n\n\n# Code\n```\nclass Solution {\npublic:\n bool lemonadeChange(vector<int>& bills) {\n if(bills[0]!=5)\n {return false;\n \n }\n int arr[3];\n int n=bills.size();\n\n for(int i=0;i<n;i++)\n {\n if(bills[i]==5)\n {\n arr[0]++;\n }\n else if(bills[i]==10)\n {\n arr[1]++;\n int x=5;\n if(arr[0]>=1)\n {\n arr[0]--;\n }\n }\n else if(bills[i]==20)\n {\n arr[2]++;\n int x=15;\n if(arr[1]>=1)\n {\n if(arr[0]>=1)\n {\n arr[1]--;\n arr[0]--;\n }\n else\n { return false;}\n }\n else if(arr[1]<1 and arr[0]>=3)\n {\n arr[0]=arr[0]-3;\n }\n else\n {\n return false;\n }\n }\n }\n return true;\n }\n};\n\n```
| 4 | 0 |
['C++']
| 1 |
lemonade-change
|
SIMPLE CPP SOLUTION || GREEDY APPROACH
|
simple-cpp-solution-greedy-approach-by-i-lxgs
|
\tbool lemonadeChange(vector& bills) {\n\t\t\tint five=0,ten=0;\n\t\t\tfor(int i=0;i<bills.size();i++)\n\t\t\t{\n\t\t\t\tif(bills[i]==5)\n\t\t\t\t\tfive++;\n\t\
|
ianujkumark
|
NORMAL
|
2022-09-17T10:56:28.772141+00:00
|
2022-09-17T10:56:28.772180+00:00
| 908 | false |
\tbool lemonadeChange(vector<int>& bills) {\n\t\t\tint five=0,ten=0;\n\t\t\tfor(int i=0;i<bills.size();i++)\n\t\t\t{\n\t\t\t\tif(bills[i]==5)\n\t\t\t\t\tfive++;\n\t\t\t\telse if(bills[i]==10)\n\t\t\t\t{\n\t\t\t\t\tif(five<1)\n\t\t\t\t\t\treturn false;\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tfive--;\n\t\t\t\t\t\tten++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tif(five==0 || (ten==0 && five<3))\n\t\t\t\t\t\treturn false;\n\t\t\t\t\telse if(ten>0)\n\t\t\t\t\t{\n\t\t\t\t\t\tten--;\n\t\t\t\t\t\tfive--;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tfive-=3;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}
| 4 | 0 |
['Greedy', 'C', 'C++']
| 0 |
lemonade-change
|
Easy C++ beats 62.41%
|
easy-c-beats-6241-by-pavandurgakumar-cyc2
|
Explanation : Finding number of 5s and 10s( during noting 10s eleminates 5s if possible if not return false) and 20s ( while noting 20s checking posiible change
|
pavandurgakumar
|
NORMAL
|
2021-10-23T06:10:53.550198+00:00
|
2021-10-23T13:33:00.601113+00:00
| 399 | false |
**Explanation :** Finding number of 5s and 10s( during noting 10s eleminates 5s if possible if not return false) and 20s ( while noting 20s checking posiible change available if not return false).\n\n```class Solution {\npublic:\n bool lemonadeChange(vector<int>& v) {\n int f=0,t=0;\n for(int i : v){\n if(i==5)\n f++;\n else if(i==10){\n t++;\n if(f>0)\n f--;\n else\n return false;\n }\n else{\n if(f && t){\n f--;\n t--;\n }\n else if(f>=3)\n f -=3;\n else\n return false;\n }\n }\n return true;\n }\n};\n```
| 4 | 0 |
[]
| 0 |
lemonade-change
|
Python 3 Easy-to-understand Better than 95%
|
python-3-easy-to-understand-better-than-58dbd
|
\n\nclass Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n change5=0\n change10=0\n change20=0\n for i in range(
|
mk_mohtashim
|
NORMAL
|
2021-06-09T06:23:46.268922+00:00
|
2021-06-09T06:24:44.884139+00:00
| 983 | false |
\n```\nclass Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n change5=0\n change10=0\n change20=0\n for i in range(len(bills)):\n if bills[i]==5:\n change5+=1\n elif bills[i]==10:\n change10+=1\n change5-=1\n elif bills[i]==20:\n if change10>0 :\n change5-=1\n change10-=1\n else:\n change5-=3\n change20+=1\n if change5<0 or change10<0 or change20<0:\n return False\n return True\n```
| 4 | 0 |
['Python', 'Python3']
| 0 |
lemonade-change
|
Javascript Clean Solution
|
javascript-clean-solution-by-zikuicai-eks8
|
\nvar lemonadeChange = function(bills) {\n let n5 = 0, n10 = 0;\n for(let i of bills) {\n if(i == 5) n5 ++;\n else if(i == 10) n5 --, n10 ++
|
zikuicai
|
NORMAL
|
2020-04-20T05:50:25.308510+00:00
|
2020-04-20T05:50:25.308559+00:00
| 252 | false |
```\nvar lemonadeChange = function(bills) {\n let n5 = 0, n10 = 0;\n for(let i of bills) {\n if(i == 5) n5 ++;\n else if(i == 10) n5 --, n10 ++;\n else if(n10 > 0) n5 --, n10 --;\n else n5 -= 3;\n if(n5 < 0) return false;\n }\n return true;\n};\n```
| 4 | 0 |
['JavaScript']
| 0 |
lemonade-change
|
Easy Solution || C++
|
easy-solution-c-by-kushhagraa-71io
|
Code
|
kushhagraa
|
NORMAL
|
2025-02-16T20:13:17.556166+00:00
|
2025-02-16T20:13:17.556166+00:00
| 182 | false |
# Code
```cpp []
class Solution {
public:
bool lemonadeChange(vector<int>& bills) {
map<int,int>mpp;
for(int i =0; i<bills.size(); i++){
if(bills[i]==5){
mpp[5]++;
}
else if(bills[i]==10){
if(mpp[5]>0){
mpp[5]--;
mpp[10]++;
}
else{
return false;
}
}
else{
if(mpp[10]>0){
if(mpp[5]>0){
mpp[5]--;
mpp[10]--;
}
else{
return false;
}
}
else if(mpp[5]>=3){
mpp[5]--;
mpp[5]--;
mpp[5]--;
}
else{
return false;
}
}
}
return true;
}
};
```
| 3 | 0 |
['Array', 'Greedy', 'C++']
| 0 |
lemonade-change
|
C++ || Beats 96.57% solutions || Simple || Easy || O(n)
|
c-beats-9657-solutions-simple-easy-on-by-jyan
|
Intuition\n Describe your first thoughts on how to solve this problem. \nThe solution uses an unordered map "mpp" to track the number of $5 and $10 bills.This i
|
Anoop08
|
NORMAL
|
2024-08-15T19:14:21.050642+00:00
|
2024-08-15T19:14:21.050673+00:00
| 17 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe solution uses an unordered map "mpp" to track the number of $5 and $10 bills.This is important because when a customer buys a lemonade with a $10 or $20,we have to give back specific amounts of change.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCreating an unordered_map<int, int> mpp to keep track of the number of $5 and $10 bills.\nUsing a loop to iterate over each element in bills vector,representing the payment from each customer.\n\nIf customer pays $5, no change is required, simply incrementing the count of $5 "mpp[5]++;".\n\nIf customer pays $10, we need to give $5 as change, so we are checking if we have have at least $5 bill "mpp[5] > 0",If its true we are decrementing the count of $5 bills "mpp[5]--;" and incrementing the count of $10 bills "mpp[10]++;".\nIf we don\'t have a $5 bill, return false.\n\nIf customer pays $20, we need to give $10 as a change, so first we are checking if we can give one $10 bill and one $5 bill as a change "(mpp[5] > 0 && mpp[10] > 0)", if we can then we are decrementing the count of both $10 and $5 bill "(mpp[5]--; mpp[10]--;)". If we cannot provide a $10 bill, then checking if we have at least three $5 bills "(mpp[5] >= 3)" if we do, give a three $5 bills as change and decrements its count "mpp[5] -= 3;"\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nTC - O(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nSC - O(1)\n\n# Code\n```\nclass Solution {\npublic:\n bool lemonadeChange(vector<int>& bills) {\n unordered_map<int , int>mpp;\n \n for(int it : bills){\n if(it == 5){\n mpp[5]++;\n }\n if(it == 10){\n if(mpp[5] > 0){\n mpp[5]--;\n mpp[10]++;\n }\n else{\n return false;\n }\n }\n else if(it == 20){\n if(mpp[5] > 0 && mpp[10] > 0){\n mpp[5]--;\n mpp[10]--;\n }\n else if(mpp[5] >= 3){\n mpp[5] -= 3;\n }\n else{\n return false;\n }\n }\n }\n return true;\n }\n};\n```
| 3 | 0 |
['C++']
| 0 |
lemonade-change
|
💡 C++ | O(n) | Simple Logic | With Full Explanation ✏️
|
c-on-simple-logic-with-full-explanation-trrtc
|
Intuition\n- Track the number of 5 and 10 bills.\n- Always try to give change using higher denomination bills (i.e., prioritize giving a 10 bill over three 5 bi
|
Tusharr2004
|
NORMAL
|
2024-08-15T09:03:24.072781+00:00
|
2024-08-15T09:03:24.072814+00:00
| 4 | false |
# Intuition\n- Track the number of 5 and 10 bills.\n- Always try to give change using higher denomination bills (i.e., prioritize giving a 10 bill over three 5 bills when handling 20 payments).\n- Return false as soon as you find that you cannot provide the correct change for a customer.\n\n# Approach\nWe will keeps track of the number of 5 and 10 bills available using two variables, `change5` and `change10`. \n\n**For each customer :**\n- if they pay with a 5 bill, no change is needed, so the count of 5 bills is simply increased. \n- If they pay with a 10 bill, a 5 bill must be returned as change. If a 5 bill is available, it is given as change; otherwise, the transaction is impossible, and the function returns `false`. \n- For a 20 bill, the preferred strategy is to give one 10 bill and one 5 bill as change (since this conserves 5 bills for future transactions). If this is not possible, three 5 bills are given instead. If neither option is available, the function returns `false`. \n\nIf all transactions are successful, the function returns `true`, indicating that correct change was provided to every customer. It\nensures that we maximize the number of smaller denomination bills, which are essential for giving change.\n\n# Complexity\n- Time complexity:\n```O(n)```\n\n- Space complexity:\n```O(1)```\n\n# Code\n```\n#pragma GCC optimize("Ofast") // Compiler directive for code optimization\n\nclass Solution {\npublic:\n bool lemonadeChange(vector<int>& bills) {\n // Optimize input/output operations\n cin.tie(0);\n cout.tie(0);\n ios::sync_with_stdio(false);\n\n int change5 = 0; // Number of $5 bills available\n int change10 = 0; // Number of $10 bills available\n\n // Loop through each customer\'s bill in the bills vector\n for (int i : bills) {\n \n // Case when the customer pays with a $5 bill\n if (i == 5) {\n change5++; // Increase the count of $5 bills\n }\n \n // Case when the customer pays with a $10 bill\n else if (i == 10) {\n change10++; // Increase the count of $10 bills\n \n // Check if we have a $5 bill to give as change\n if (change5 > 0) {\n change5--; // Give one $5 bill as change\n } else {\n return false; // If no $5 bill is available, return false\n }\n }\n \n // Case when the customer pays with a $20 bill\n else {\n // Prefer to give one $10 bill and one $5 bill as change\n if (change10 > 0 && change5 > 0) {\n change10--; // Give one $10 bill\n change5--; // Give one $5 bill\n }\n // If no $10 bill is available, give three $5 bills as change\n else if (change5 >= 3) {\n change5 -= 3; // Reduce three $5 bills\n } \n // If we can\'t provide the correct change, return false\n else {\n return false;\n }\n }\n }\n \n // If we were able to provide correct change for all customers, return true\n return true;\n }\n};\n\n```\n\n\n\n\n\n# Ask any doubt !!!\nReach out to me \uD83D\uDE0A\uD83D\uDC47\n\uD83D\uDD17 https://tusharbhardwa.github.io/Portfolio/\n\n\n
| 3 | 0 |
['C++']
| 0 |
lemonade-change
|
One of the easiest Approach in Basic way with explanation .Here you can understand it very easily,
|
one-of-the-easiest-approach-in-basic-way-xvj2
|
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
|
raeezrazz
|
NORMAL
|
2024-08-15T08:08:33.823573+00:00
|
2024-08-15T08:08:33.823595+00:00
| 316 | false |
# 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```\n/**\n * @param {number[]} bills\n * @return {boolean}\n */\nvar lemonadeChange = function(bills) {\n\n//create a object to calculate your currrent balance of money\n let obj ={\n five:0,\n ten:0,\n \n }\n//itrate through the amount and do curresponding changes in the obj (balance) and return false if you get out of money to give balance to the customer\n\n\n for(let i = 0 ; i < bills.length ;i++){\n console.log(obj)\n if(bills[i] == 5){\n obj.five +=5 \n }else if(bills[i] == 20){\n if(obj.ten >=10 && obj.five >=5){\n obj.ten -=10\n obj.five -=5\n }else if(obj.five >=15){\n obj.five -=15\n }else{\n return false\n }\n }else{\n console.log(i,bills[i])\n if(obj.five >=5){\n obj.ten +=10\n obj.five -=5\n }else{\n return false\n }\n }\n }\n\n //return true means you have successfully gave the balance to the customer \n return true\n\n\n};\n```
| 3 | 0 |
['JavaScript']
| 1 |
lemonade-change
|
Easy logical solution
|
easy-logical-solution-by-ajithglady-hdcj
|
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
|
ajithglady
|
NORMAL
|
2024-08-15T06:24:10.432226+00:00
|
2024-08-15T06:24:10.432251+00:00
| 197 | false |
# 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```\n/**\n * @param {number[]} bills\n * @return {boolean}\n */\nvar lemonadeChange = function(bills) {\n let five = 0\n let ten = 0\n let twenty = 0\n for(let i=0 ; i<bills.length ; i++){\n if(bills[i] === 5){\n five++\n }else if(bills[i] === 10){\n if(five >0){\n five--\n ten++\n }else{\n return false\n }\n }else if(bills[i] === 20){\n if(five > 0 && ten > 0){\n five--\n ten--\n }else if(five > 2){\n five -= 3\n }else{\n return false\n }\n }\n }\n return true\n};\n```
| 3 | 0 |
['JavaScript']
| 0 |
lemonade-change
|
Lemonade Change (Easy Explanation - 100 % beats) - 1ms
|
lemonade-change-easy-explanation-100-bea-jvkl
|
Intuition\n Describe your first thoughts on how to solve this problem. \n- The lemonade costs 5 dollars,the customer might pay either 5,10 or 20 dollars.If they
|
RAJESWARI_P
|
NORMAL
|
2024-08-15T05:49:56.455958+00:00
|
2024-08-15T05:49:56.455989+00:00
| 55 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- The lemonade costs 5 dollars,the customer might pay either 5,10 or 20 dollars.If they pay 10 dollars,we have to give them a change of 5 dollars and if the customer pay 20 dollars,we have to pay them a change of 15 dollars, ie. either 3 5dollars or 1 5dollars and 1 10dollars. \n\n- Initially we might not have any change,so if the first customer gives 10 or 20 dollars,we might not able to provide them with change,hence we should return false.\n\n- If we might able to provide all customer with the correct change,we should return true.Otherwise,we may return false.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n**Keep track of available change**:\n\n-The available change may be keep track in terms of number 10 dollars and 5 dollars available,this might help us to determine whether we can provide a customer a change or not.So initialize the two variables five and ten as 0.\n\n**Condition Checking**:\n\n**Customer pays exactly 5 dollars**:\n\n-There is no need of providing any change,so we can increment the five to 1.So that it can be useful later for providing change.\n\n**Customer pays 10 dollars**:\n\n-If the customer pays 10 dollars,the actual cost of the lemonade was 5,So the change we have to give is 10 - 5 = 5 dollars.\n \n Change amount = customer paid amount - lemonade cost (5 dollars)\n \n-Hence this is the time to check if the 5 dollars is available to him or not to provide the customer with the change.So we check the tracking variable five > 0,hence we decrement the count of five and increment the count of ten.\n \n**Customer pays 20 dollars**:\n\n-If the customer pays 20 dollars,the change we have to give to the customer is 15 dollars.\n\n-It can be of any form,that can be 1 10dollars and 1 5dollars or 3 5dollars.\n\n-So can check the availability of that by checking if ten>0 and five > 0,then we can provide the customer with 1 10dollar and 1 5dollar or we can check if five >= 3,if so we can provide customer with 3 five dollars.\n\n-If both the ways are not possible,then we may not able to provide customer with the change,So we return false.\n\n# Complexity\n- Time complexity: **O(n)**\n n -> number of elements in the bill array.\n- The program iterates through bill array only once\n- Each operation inside the loop takes constant time **O(1)**\n\nHence Overall Time Complexity is **O(n)**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:**O(1)**\n- The program takes constant amount of extra space : two integer variables(ten and five) to keep track of 10 and 5 dollars respectively.\n- No additional space is used that grows with input size.\n\nHence Overall Space Complexity is **O(1)**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public boolean lemonadeChange(int[] bills) {\n int five = 0;\n int ten = 0;\n \n for (int bill : bills) {\n if (bill == 5) {\n five++;\n } else if (bill == 10) {\n if (five > 0) {\n five--;\n ten++;\n } else {\n return false;\n }\n } else { // bill == 20\n if (ten > 0 && five > 0) {\n ten--;\n five--;\n } else if (five >= 3) {\n five -= 3;\n } else {\n return false;\n }\n }\n }\n \n return true;\n }\n}\n```
| 3 | 0 |
['Array', 'Greedy', 'Java']
| 1 |
lemonade-change
|
easy way using if/elif💯💯
|
easy-way-using-ifelif-by-varshuvarshitha-zpm8
|
\n\n# Code\n\nclass Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n fives= 0 \n tens = 0 \n for i in bills:\n
|
varshuvarshitha20
|
NORMAL
|
2024-08-15T04:23:03.730550+00:00
|
2024-08-15T04:23:03.730586+00:00
| 516 | false |
\n\n# Code\n```\nclass Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n fives= 0 \n tens = 0 \n for i in bills:\n if(i==5):\n fives+=1 \n elif(i==10):\n tens+=1 \n if(fives>0):\n fives-= 1 \n else:\n return False\n else:\n if(tens>0 and fives>0):\n tens-=1 \n fives-=1 \n elif(fives>2):\n fives-=3\n else:\n return False\n return True\n```
| 3 | 0 |
['Python3']
| 0 |
lemonade-change
|
Java Solution for Lemonade Change Problem
|
java-solution-for-lemonade-change-proble-n7he
|
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem is essentially about managing change efficiently, given the constraints on
|
Aman_Raj_Sinha
|
NORMAL
|
2024-08-15T02:32:11.821791+00:00
|
2024-08-15T02:32:11.821811+00:00
| 422 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is essentially about managing change efficiently, given the constraints on the types of bills you can receive and the need to provide exact change. The challenge lies in ensuring that for every $10 or $20 bill received, you have the appropriate combination of $5 and $10 bills to provide the correct change. The greedy approach works here: always try to give the largest possible bills as change first, as this leaves you with smaller bills that are more flexible for future transactions\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1.\tTrack the bills: Use two counters, five and ten, to keep track of the number of $5 and $10 bills you have.\n2.\tProcess each bill:\n\t\u2022\tIf a customer pays with a $5 bill, simply increase the five counter.\n\t\u2022\tIf a customer pays with a $10 bill, check if you have at least one $5 bill to provide change. If you do, decrement the five counter and increase the ten counter. If not, return false because you can\u2019t provide the correct change.\n\t\u2022\tIf a customer pays with a $20 bill, try to give $15 in change. Preferably, this should be one $10 bill and one $5 bill (as this maximizes the number of $5 bills left). If you can\u2019t do that, check if you can give three $5 bills as change. If neither option is available, return false.\n3.\tReturn true if you successfully process all customers, meaning you could provide correct change every time.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n), where n is the length of the bills array. We process each bill exactly once, and all operations within the loop are O(1).\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1), as we only use a constant amount of additional space (five and ten counters).\n\n# Code\n```\nclass Solution {\n public boolean lemonadeChange(int[] bills) {\n int five = 0, ten = 0;\n \n for (int bill : bills) {\n if (bill == 5) {\n five++;\n } else if (bill == 10) {\n if (five == 0) {\n return false;\n }\n five--;\n ten++;\n } else if (bill == 20) {\n if (ten > 0 && five > 0) {\n ten--;\n five--;\n } else if (five >= 3) {\n five -= 3;\n } else {\n return false;\n }\n }\n }\n \n return true;\n }\n}\n```
| 3 | 0 |
['Java']
| 1 |
lemonade-change
|
Functional JavaScript | 1-liner | (b,f=0,t=0)=>b.every(x=>x==5?++f:(x==10?++t:t?--t:f-=2,f-->0))
|
functional-javascript-1-liner-bf0t0bever-iej6
|
Intuition\nKeep track of number of $5 and $10 that we have.\nFor every $20 first give $10, and only if out of $10, give 3 $5.\nIf we don\'t have bills to give,
|
Serhii_Hrynko
|
NORMAL
|
2024-08-14T00:21:49.058481+00:00
|
2024-09-10T17:54:58.288351+00:00
| 173 | false |
# Intuition\nKeep track of number of `$5` and `$10` that we have.\nFor every `$20` first give `$10`, and only if out of `$10`, give 3 `$5`.\nIf we don\'t have bills to give, return false.\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nlemonadeChange=(b,f=0,t=0)=>b.every(x=>x==5?++f:(x==10?++t:t?--t:f-=2,f-->0))\n```\n\nExpanded:\n```\nlemonadeChange=(\n bills,\n fives=0,\n tens=0\n)=>bills.every(bill=>\n bill==5\n ?++fives\n :(\n bill==10\n ?++tens\n :tens>0\n ?--tens\n :fives-=2,\n // there was enough $5 bills to give a change\n fives-- > 0\n )\n)\n```
| 3 | 0 |
['JavaScript']
| 1 |
lemonade-change
|
Easiest python solution
|
easiest-python-solution-by-avinash_singh-yyka
|
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
|
avinash_singh_13
|
NORMAL
|
2024-05-19T16:42:46.518875+00:00
|
2024-05-19T16:42:46.518902+00:00
| 195 | false |
# 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 lemonadeChange(self, bills: List[int]) -> bool:\n a,b=0,0\n for i in range(len(bills)):\n if bills[i]==5:\n a+=1\n elif bills[i]==10:\n b+=1\n if not a:\n return False\n a-=1\n else:\n if a and b:\n a-=1\n b-=1\n elif a>2:\n a-=3\n else:\n return False\n return True\n```
| 3 | 0 |
['Python3']
| 0 |
lemonade-change
|
Lemonade Change using Switch case
|
lemonade-change-using-switch-case-by-yas-thji
|
Intuition\nTo solve the problem you just need to know the switch case,increment decrement and condtional statement.\n\n# Approach\nyou need to assign a varaible
|
Yashvanth4510
|
NORMAL
|
2024-03-19T09:14:20.242455+00:00
|
2024-03-19T09:14:20.242502+00:00
| 426 | false |
# Intuition\nTo solve the problem you just need to know the switch case,increment decrement and condtional statement.\n\n# Approach\nyou need to assign a varaible for each number\n```\n int sum5 = 0, sum10 = 0,sum20 = 0;\n```\n1. Then create a for loop and set the condition as the array length\n2. Inside the for loop assign the switch case with three conditions:\n> switch(arr[i]){\ncase 5:\ncase 10:\ncase 20:\n}\n3. In each case set the increament of the variable\n4. then give condiotion if the previous increament is above the specific count else return **false**\n```\nif(sum5 > 0)\nif(sum5 > 0 && sum10 > 0)\n```\n5. then finally return **true**\n\n\n\n# Complexity\n- Time complexity:\nO(1)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\n public boolean lemonadeChange(int[] bills) {\n int sum5 = 0, sum10 = 0,sum20 = 0;\n for(int i =0 ;i<bills.length;i++){\n\n switch(bills[i]){\n case 5:\n sum5++;\n break;\n case 10:\n if(sum5 > 0){\n sum5--;\n sum10++;\n }else{\n return false;\n }\n break;\n\n case 20:\n if(sum5 > 0 && sum10 > 0){\n sum20++;\n sum5--;\n sum10--;\n }else if(sum5>2){\n sum20++;\n sum5 -=3; \n }else{\n return false;\n }\n break;\n }\n \n }\n\n return true;\n }\n}\n```
| 3 | 0 |
['Array', 'Greedy', 'Java']
| 1 |
lemonade-change
|
easy code in c++
|
easy-code-in-c-by-shobhit_panuily-tiw8
|
\n\n# Code\n\nclass Solution {\npublic:\n bool lemonadeChange(vector<int>& bills) {\n int n = bills.size();\n long long int change = 0;\n
|
Shobhit_panuily
|
NORMAL
|
2024-02-27T17:45:19.101144+00:00
|
2024-02-27T17:45:19.101176+00:00
| 593 | false |
\n\n# Code\n```\nclass Solution {\npublic:\n bool lemonadeChange(vector<int>& bills) {\n int n = bills.size();\n long long int change = 0;\n int fives = 0, tens = 0;\n for (int i = 0; i < n; i++) {\n if (bills[i] == 5) {\n fives++;\n } \n else if (bills[i] == 10) {\n if (fives == 0) {\n return false;\n }\n fives--;\n tens++;\n } \n else { \n if (tens > 0 && fives > 0) {\n tens--;\n fives--;\n } \n else if (fives >= 3) {\n fives -= 3;\n } \n else {\n return false;\n }\n }\n }\n return true;\n }\n};\n\n```
| 3 | 0 |
['C++']
| 0 |
lemonade-change
|
Super Easy Solution
|
super-easy-solution-by-himanshu__mehra-urs3
|
Intuition:\nThe approach to solving this problem involves keeping track of the number of 5 and 10 bills we have in hand. Whenever a customer pays with a 5 bill
|
himanshu__mehra__
|
NORMAL
|
2023-07-15T07:24:44.392039+00:00
|
2023-07-19T14:50:01.919353+00:00
| 656 | false |
# Intuition:\nThe approach to solving this problem involves keeping track of the number of 5 and 10 bills we have in hand. Whenever a customer pays with a 5 bill, we simply increment the count of 5 bills. If a customer pays with a 10 bill, we decrement the count of $5 bills if available. If we don\'t have any 5 bills left at this point, we cannot provide change, so we return false. If the customer pays with a 20 bill, we first try to give change using a 10 bill and a 5 bill (if available) and then, as a fallback, three 5 bills. If we cannot provide change in either of these ways, we return false.\n\n# Algorithm:\nInitialize two variables, fives and tens, to keep track of the count of $5 and $10 bills, respectively.\nIterate through the bills array, and for each bill:\na. If the bill is $5, increment the fives count.\nb. If the bill is $10, increment the tens count and decrement the fives count by 1 (if available). If fives is zero at this point, return false.\nc. If the bill is $20:\nFirst, try to give change using a $10 bill and a $5 bill. Decrement both tens and fives counts by 1 (if available).\nIf we couldn\'t give change using the above step, try giving change using three $5 bills. Decrement fives count by 3 (if available).\nIf we still cannot give change, return false.\nIf we successfully provide change for all customers, return true.\nComplexity Analysis:\n\n# Time Complexity:\n The algorithm iterates through the bills array once, which takes O(n) time, where n is the number of customers.\n# Space Complexity:\n The algorithm uses two integer variables, fives and tens, which occupy constant space, so the space complexity is O(1).\nOverall, the algorithm has a linear time complexity of O(n) and a constant space complexity of O(1).\n\n\n\n\n\n# Code\n```\nclass Solution {\npublic:\n bool lemonadeChange(vector<int>& bills) {\n int fives=0; int tens=0;\n int n= bills.size();\n for (int i=0; i<n; i++){\n if (bills[i]==5)fives++;\n if (bills[i]==10){\n tens++;\n if (fives==0)return false;\n fives--;\n }\n if (bills[i]==20){\n if (tens>0 && fives>0){\n tens--;\n fives--;\n }\n else if (fives>=3){\n fives-=3;\n }\n else return false;\n }\n }\n return true;\n }\n};\n```
| 3 | 0 |
['C++']
| 1 |
lemonade-change
|
[JAVA] easy self-explanatory code
|
java-easy-self-explanatory-code-by-jugan-s6zd
|
\n\n# Complexity\n- Time complexity: O(N)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(1)\n Add your space complexity here, e.g. O(n) \n
|
Jugantar2020
|
NORMAL
|
2023-07-03T07:24:33.387087+00:00
|
2023-07-03T07:24:33.387121+00:00
| 707 | false |
\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public boolean lemonadeChange(int[] bills) {\n int five = 0, ten = 0;\n for(int i : bills) {\n if(i == 5) five ++;\n else if(i == 10) {\n if(five > 0) {\n five --;\n ten ++;\n }\n else return false;\n }\n else {\n if(ten > 0 && five > 0) {\n five --;\n ten --;\n }\n else if(five >= 3) \n five -= 3;\n else \n return false; \n }\n } \n return true;\n }\n}\n```
| 3 | 0 |
['Array', 'Greedy', 'Java']
| 0 |
lemonade-change
|
C++ Solution || Comments || Easy || Explained
|
c-solution-comments-easy-explained-by-is-fl58
|
Intuition\n Describe your first thoughts on how to solve this problem. \nCreate 3 variable to count no. of $coins$ like cnt5 = 0, cnt10 = 0, cnt20 = 0 and now i
|
isarthaksharma1092
|
NORMAL
|
2023-06-22T18:46:41.336435+00:00
|
2023-06-22T18:46:41.336463+00:00
| 680 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCreate 3 variable to count no. of $coins$ like `cnt5 = 0, cnt10 = 0, cnt20 = 0` and now increment and decrement according to the received amount.\n\n*Refer code for more details*\n\n---\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n---\n\n# Code\n```\nclass Solution {\npublic:\n bool lemonadeChange(vector<int>& bills) \n {\n int cnt5 = 0,cnt10 = 0,cnt20 = 0;\n\n //handling the case\n //if no 5 coin is present than no change\n if(bills[0] != 5){\n return false;\n }\n\n for(int i = 0;i<bills.size();i++)\n {\n if(bills[i] == 5)\n {\n cnt5++;\n }\n else if(bills[i] == 10)\n {\n //if we have $5 coin fine \n //otherwise no change available\n if(cnt5 > 0)\n {\n cnt5--;\n cnt10++;\n }\n else{return false;}\n }\n else if(bills[i]==20)\n {\n //case1\n //one $10 coin and $5 coin needed\n if(cnt10>0 && cnt5>0){cnt5--;cnt10--;cnt20++;}\n\n //case2\n //we need three $5 coins\n else if(cnt5>=3){cnt5 -= 3;cnt20++;}\n\n //otherwise no change\n else{return false;}\n }\n }\n return true;\n }\n};\n```\n* ***Try to understand the code rather than coping.***\n* ***If you liked my work than upvote my solution.***\n\n\t\t\t\t\t\t\t\t\t\t AND\n\t\t\t\t\t\t\t\t\t\t \n\t\t\t\t\t\t\t\t**** Happy Coding ****\n\t\t\t\t\t\t**** Keep Solving, Keep Upgrading **** \n
| 3 | 0 |
['Array', 'C++']
| 0 |
lemonade-change
|
Clean and ordered Solution using Stack
|
clean-and-ordered-solution-using-stack-b-28uw
|
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
|
RohanShetty2003
|
NORMAL
|
2023-06-02T08:11:02.468479+00:00
|
2023-06-02T08:11:02.468522+00:00
| 1,472 | false |
# 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 public boolean lemonadeChange(int[] bills) {\n Stack<Integer> stackOf5=new Stack();\n Stack<Integer> stackOf10=new Stack();\n\n for(int i=0;i<bills.length;i++)\n {\n int input=bills[i];\n if(input==5)\n {\n stackOf5.push(input);\n }\n\n else if(input==10)\n {\n stackOf10.push(input);\n if(stackOf5.empty())\n return false;\n else\n stackOf5.pop();\n }\n\n else if(input==20)\n {\n if(!stackOf10.empty())\n {\n stackOf10.pop();\n if(stackOf5.empty())\n return false;\n else\n stackOf5.pop();\n }\n\n else if(!stackOf5.empty())\n {\n for(int j=0;j<3;j++)\n {\n if(stackOf5.empty())\n {\n return false;\n }\n stackOf5.pop();\n }\n }\n\n else\n {\n return false;\n }\n }\n }\n return true;\n\n }\n}\n```
| 3 | 0 |
['Stack', 'Java']
| 0 |
lemonade-change
|
Super Easy 8 lines Java Code || Only if else Statements
|
super-easy-8-lines-java-code-only-if-els-f7wu
|
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
|
jashan_pal_singh_sethi
|
NORMAL
|
2023-05-22T05:46:02.830356+00:00
|
2023-05-22T05:46:02.830387+00:00
| 371 | false |
# 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 public boolean lemonadeChange(int[] bills) {\n int five = 0, ten = 0;\n for (int i : bills) {\n if (i == 5) five++;\n else if(i == 10) {five--; ten++;}\n else if(ten > 0 && five>=1){ ten--; five--;}\n else{five -= 3;}\n if (five < 0) return false;\n }\n return true;\n }\n} \n```
| 3 | 0 |
['Array', 'Math', 'Greedy', 'Java']
| 0 |
lemonade-change
|
✅ Easy C# solution
|
easy-c-solution-by-kamronsaliev-u25u
|
Code\n\npublic class Solution \n{\n public bool LemonadeChange(int[] bills)\n {\n var five = 0;\n var ten = 0;\n\n for (var i = 0; i
|
KamronSaliev
|
NORMAL
|
2023-02-25T13:16:25.653528+00:00
|
2023-02-25T13:16:38.341901+00:00
| 59 | false |
# Code\n```\npublic class Solution \n{\n public bool LemonadeChange(int[] bills)\n {\n var five = 0;\n var ten = 0;\n\n for (var i = 0; i < bills.Length; i++)\n {\n if (bills[i] == 5)\n {\n five++;\n }\n else if (bills[i] == 10)\n {\n five--;\n ten++;\n }\n else if (ten > 0)\n {\n five--;\n ten--;\n }\n else\n {\n five -= 3;\n }\n\n if (five < 0)\n {\n return false;\n }\n }\n\n return true;\n }\n}\n```\n\n\n
| 3 | 0 |
['Greedy', 'C#']
| 1 |
lemonade-change
|
IF-ELSE || EASY TO UNDERSTAND || JAVA CODE
|
if-else-easy-to-understand-java-code-by-qww76
|
\nclass Solution {\n\n public boolean lemonadeChange(int[] bills) {\n int a = 0, b = 0;\n\n for (int i = 0; i < bills.length; i++) {\n
|
priyankan_23
|
NORMAL
|
2022-08-30T14:10:00.917782+00:00
|
2022-08-30T14:10:00.917827+00:00
| 397 | false |
```\nclass Solution {\n\n public boolean lemonadeChange(int[] bills) {\n int a = 0, b = 0;\n\n for (int i = 0; i < bills.length; i++) {\n if (bills[i] == 5) {\n a++;\n }\n if (bills[i] == 10) {\n if (a == 0) return false;\n\n b++;\n\n a--;\n }\n if (bills[i] == 20) {\n if (a > 0 && b > 0) {\n a--;\n b--;\n } else if (a >= 3) {\n a -= 3;\n } else return false;\n }\n }\n return true;\n }\n}\n```
| 3 | 0 |
['Array']
| 2 |
lemonade-change
|
Java easy solution
|
java-easy-solution-by-yxp5-am09
|
Just list out all correct possibilities, return false if no case matches.\n```\npublic boolean lemonadeChange(int[] bills) {\n if (bills[0] != 5) return
|
yxp5
|
NORMAL
|
2022-08-17T01:36:22.843033+00:00
|
2022-08-17T01:36:22.843064+00:00
| 906 | false |
Just list out all correct possibilities, return false if no case matches.\n```\npublic boolean lemonadeChange(int[] bills) {\n if (bills[0] != 5) return false;\n \n int fives = 0, tens = 0;\n for (int bill : bills) {\n if (bill == 5) {\n fives++;\n continue;\n } else if (bill == 10 && fives != 0) {\n fives--;\n tens++;\n continue;\n } else if (bill == 20) {\n if (tens != 0 && fives != 0) {\n tens--;\n fives--;\n continue;\n } else if (fives >= 3) {\n fives -= 3;\n continue;\n }\n }\n return false;\n }\n return true;\n }
| 3 | 0 |
['Java']
| 1 |
lemonade-change
|
Greedy Approach with C++ Simple
|
greedy-approach-with-c-simple-by-bhagwat-hawu
|
\n/*\nThe Approach is Greedy if we have max change note then change with that\nEx:- for 20 first we look for one 10\'s note if we have and one 5\'s note but if
|
bhagwat_singh_cse
|
NORMAL
|
2022-08-06T03:58:01.642694+00:00
|
2022-08-06T03:58:01.642724+00:00
| 179 | false |
```\n/*\nThe Approach is Greedy if we have max change note then change with that\nEx:- for 20 first we look for one 10\'s note if we have and one 5\'s note but if we do not have 10\'s note then change with 3 5\'s notes.\n*/\n\nbool lemonadeChange(vector<int>& bills) {\n\n\t\t// variable for count of notes we have of each\n int count5=0,count10=0,count20=0;\n \n for(int val:bills){\n if(val==5)count5++;\n if(val==10){\n count5--;\n count10++;\n }\n if(val==20){\n count20++;\n if(count10>0){\n count10--;\n count5--;\n }\n else{\n count5-=3;\n }\n }\n \n if(count5<0 or count10<0 or count20<0)return false;\n \n }\n return true;\n \n }\n```
| 3 | 0 |
['Greedy']
| 0 |
lemonade-change
|
Python3 O(n) || O(1) # Runtime: 1159ms 49.65% Memory: 18mb 49.96%
|
python3-on-o1-runtime-1159ms-4965-memory-zwe4
|
\nclass Solution:\n# O(n) || O(1)\n# Runtime: 1159ms 49.65% Memory: 18mb 49.96%\n def lemonadeChange(self, bills: List[int]) -> bool:\n fiveBills,
|
arshergon
|
NORMAL
|
2022-06-23T13:37:37.507060+00:00
|
2022-06-23T13:37:37.507092+00:00
| 688 | false |
```\nclass Solution:\n# O(n) || O(1)\n# Runtime: 1159ms 49.65% Memory: 18mb 49.96%\n def lemonadeChange(self, bills: List[int]) -> bool:\n fiveBills, tenBills = 0, 0\n\n for i in bills:\n if i == 5:\n fiveBills += 1\n elif i == 10:\n tenBills += 1\n fiveBills -= 1\n elif tenBills > 0:\n tenBills -= 1\n fiveBills -= 1\n else:\n fiveBills -= 3\n\n if fiveBills < 0:\n return False\n\n\n return True \n```
| 3 | 0 |
['Python', 'Python3']
| 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.