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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mini-parser | Java - Recursive Solution with FULL explanation | java-recursive-solution-with-full-explan-5ava | Since the question mentions nested structure, use of recursion is necessary.\n\nAlso, it\'s mentioned that the element is either an integer or list of NestedInt | parin2 | NORMAL | 2020-05-04T09:08:18.564645+00:00 | 2020-05-04T09:08:18.564696+00:00 | 175 | false | Since the question mentions *nested* structure, use of recursion is necessary.\n\nAlso, it\'s mentioned that the element is *either an integer or list of NestedIntegers*. So, **the base-case will be, the string which does not start with \'[\'.** - which means, the nested integer contains only one integer.\n\nNow we have got our base-case, let\'s focus on how we can recurse. \n* if the base-condition is not satisfied, that means, what we have a serialized version of *list of nested integers.* And such a list will always be enclosed with `[` and `]`. So, get rid of it.\n* Process individual elements separated by `,` and deserialize them recursively.\n* Also, if we encounter a nested integer in between, use a stack to get the last `]` for that element and process that nested integer separately through recursion. \n\nFor example, let\'s take a complicated string as below:\n```\n"[123,456,[788,799,833],[[]],10,[]]"\n```\n\nClearly, the given string won\'t satisfy the base condition. So, getting rid of surrounding brackets, the string becomes\n```\n"123,456,[788,799,833],[[]],10,[]"\n```\n\nAfter that, extract individual elements of this outer-most nested integer.\n\n```\n"123" // this will satisfy the base-condition in the next recursion call\n```\n```\n"456" // this will satisfy the base-condition in the next recursion call\n```\n```\n"[788,799,833]" // use stack to extract the perfect nested integer enclosed between brackets\n```\n```\n"[[]]" // use stack to extract the perfect nested integer enclosed between outer brackets\n```\n\n```\n"10" // this will satisfy the base-condition in the next recursion call\n```\n\n```\n[] // use stack to extract the perfect nested integer enclosed between outer brackets\n```\n\nThe **Java** implementation for this approach is:\n\n```\npublic NestedInteger deserialize(String s) {\n\tNestedInteger res = new NestedInteger();\n\tif (s.charAt(0) != \'[\') {\n\t\tint num = Integer.parseInt(s);\n\t\tres.setInteger(num);\n\t\treturn res;\n\n\t}\n\n\ts = s.substring(1, s.length() - 1);\n\tif (s.isEmpty()) {\n\t\treturn new NestedInteger();\n\n\t} else {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tfor (int i = 0; i < s.length(); i++) {\n\t\t\tif (s.charAt(i) == \'[\') {\n\t\t\t\tStack<Character> stack = new Stack<>();\n\t\t\t\tstack.push(s.charAt(i));\n\t\t\t\tint j = i+1;\n\t\t\t\twhile (j < s.length() && !stack.isEmpty()) {\n\t\t\t\t\tif (s.charAt(j) == \'[\') {\n\t\t\t\t\t\tstack.push(\'[\');\n\t\t\t\t\t} else if (s.charAt(j) == \']\') {\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t}\n\t\t\t\t\t++j;\n\t\t\t\t}\n\n\t\t\t\tres.add(deserialize(s.substring(i, j)));\n\t\t\t\ti = j;\n\t\t\t} else if (s.charAt(i) == \',\') {\n\t\t\t\tres.add(deserialize(sb.toString()));\n\t\t\t\tsb = new StringBuilder();\n\t\t\t} else {\n\t\t\t\tsb.append(s.charAt(i));\n\t\t\t}\n\t\t}\n\t\tif (sb.length() != 0) {\n\t\t\tres.add(deserialize(sb.toString()));\n\t\t}\n\t}\n\treturn res;\n}\n```\n\n\n\n\n\n | 1 | 0 | [] | 0 |
mini-parser | Python Iterative | python-iterative-by-majgawali-82rs | \nclass Solution:\n def deserialize(self, s: str) -> NestedInteger:\n \n if (len(s) == 0):\n return NestedInteger()\n elif (s | majgawali | NORMAL | 2020-04-18T05:59:00.577478+00:00 | 2020-04-18T05:59:00.577508+00:00 | 222 | false | ```\nclass Solution:\n def deserialize(self, s: str) -> NestedInteger:\n \n if (len(s) == 0):\n return NestedInteger()\n elif (s[0] != \'[\'):\n return NestedInteger(int(s))\n \n number=\'\'\n stack = [NestedInteger()]\n \n for char in s:\n if char.isdigit() or char==\'-\':\n number += char\n elif char == \',\':\n if (number):\n stack[-1].add(NestedInteger(int(number)))\n number=\'\'\n elif char == \'[\':\n stack.append(NestedInteger())\n else:\n if (number):\n stack[-1].add(NestedInteger(int(number)))\n number=\'\'\n haha = stack.pop()\n stack[-1].add(haha);\n \n ans = stack[0]\n return ans.getList()[0]\n``` | 1 | 0 | [] | 0 |
mini-parser | Java solution uses recursive | java-solution-uses-recursive-by-akiramon-e3ha | case 1: s = "123" -> 123\ncase 2: [] -> return new NestedInteger()\ncase 3: [123, 456, 789, [1, 2, 3], [4, 5, 6]]\n\n\nclass Solution {\n public NestedIntege | akiramonster | NORMAL | 2020-04-06T22:19:51.542216+00:00 | 2020-04-06T22:19:51.542256+00:00 | 99 | false | case 1: s = "123" -> 123\ncase 2: [] -> return new NestedInteger()\ncase 3: [123, 456, 789, [1, 2, 3], [4, 5, 6]]\n\n```\nclass Solution {\n public NestedInteger deserialize(String s) {\n NestedInteger res = new NestedInteger();\n if (s == null || s.length() == 0) return res;\n if (s.charAt(0) != \'[\') { // case 1\n res.setInteger(Integer.parseInt(s));\n return res;\n }\n if (s.length() <= 2) return res; // case 2 \n int start = 1, count = 0;\n for (int i = 1; i < s.length(); i++) { // case 3\n char c = s.charAt(i);\n if (count == 0 && (c == \',\' || i == s.length() - 1)) {\n res.add(deserialize(s.substring(start, i)));\n start = i + 1;\n } else if (c == \'[\') count++;\n else if (c == \']\') count--;\n }\n return res;\n\n }\n}\n``` | 1 | 0 | [] | 0 |
mini-parser | Java 29.27% time 30% space, Iterative w/ stack | java-2927-time-30-space-iterative-w-stac-cd0q | ````\nclass Solution {\n public NestedInteger deserialize(String s) {\n if(!s.startsWith("["))return new NestedInteger(Integer.valueOf(s));\n S | robsalcedo | NORMAL | 2020-03-13T05:13:21.823507+00:00 | 2020-03-13T05:13:21.823543+00:00 | 232 | false | ````\nclass Solution {\n public NestedInteger deserialize(String s) {\n if(!s.startsWith("["))return new NestedInteger(Integer.valueOf(s));\n Stack<NestedInteger> st=new Stack<NestedInteger>();\n NestedInteger res = new NestedInteger();\n st.push(res);\n int start=1;\n for(int i=1;i<s.length();i++){\n if(s.charAt(i)==\'[\'){\n NestedInteger cur=new NestedInteger();\n st.peek().add(cur);\n st.push(cur);\n start=i+1;\n }else if(s.charAt(i)==\']\' || s.charAt(i)==\',\'){\n if(start<i){\n int end=i;\n String n=s.substring(start,end);\n st.peek().add(new NestedInteger(Integer.valueOf(n)));\n }\n start=i+1;\n if(s.charAt(i)==\']\')st.pop();\n }\n }\n return res;\n }\n} | 1 | 0 | ['Iterator', 'Java'] | 0 |
mini-parser | Swift Solution using Stack | swift-solution-using-stack-by-alptekin35-dgef | \nclass Solution {\n func deserialize(_ s: String) -> NestedInteger {\n var stack:[NestedInteger] = []\n var current:NestedInteger = NestedInte | alptekin35 | NORMAL | 2020-01-16T23:01:35.585622+00:00 | 2020-01-16T23:01:35.585673+00:00 | 121 | false | ```\nclass Solution {\n func deserialize(_ s: String) -> NestedInteger {\n var stack:[NestedInteger] = []\n var current:NestedInteger = NestedInteger()\n let head = current\n var currentItem = ""\n var negative = false\n for item in s{\n if item == "["{\n let nItem = NestedInteger()\n stack.append(current)\n current = nItem\n }else if item == "]"{\n if let number = Int(currentItem) {\n let nItem = NestedInteger()\n nItem.setInteger(negative == false ? number : number * -1)\n current.add(nItem)\n currentItem = ""\n negative = false\n }\n let lastItem = stack.popLast()!\n lastItem.add(current)\n current = lastItem\n \n }else if item == ","{\n if let number = Int(currentItem) {\n let nItem = NestedInteger()\n nItem.setInteger(negative == false ? number : number * -1)\n current.add(nItem)\n currentItem = ""\n negative = false\n }\n }else if let digit = Int(String(item)){\n currentItem += String(item)\n }else if item == "-"{\n negative = true\n }\n }\n if let number = Int(currentItem) {\n let nItem = NestedInteger()\n nItem.setInteger(negative == false ? number : number * -1)\n current.add(nItem)\n currentItem = ""\n }\n return head.getList().first!\n }\n}\n``` | 1 | 0 | ['Stack', 'Swift'] | 0 |
mini-parser | python solution to parse the input string into a native nested list in python | python-solution-to-parse-the-input-strin-5cis | Not sure why we need a NestedInteger type in python since python could already represent such values. The parse step and creation of NestedInteger could be com | e2718281828 | NORMAL | 2020-01-03T04:47:13.210562+00:00 | 2020-01-03T04:47:13.210611+00:00 | 249 | false | Not sure why we need a NestedInteger type in python since python could already represent such values. The parse step and creation of NestedInteger could be combined into one step.\n\n```\nclass Solution:\n def deserialize(self, s: str) -> NestedInteger:\n if s[0].isdigit():\n return NestedInteger(int(s))\n lis = parse_list_expression(s)\n res = helper(lis)\n return res\n \ndef helper(x):\n if type(x) is int:\n return NestedInteger(x)\n res = NestedInteger()\n for e in x:\n res.add(helper(e))\n return res\n \ndef parse_list_expression(s):\n lis = []\n for c in s:\n if c == \'[\':\n if lis and lis[-1] == \',\':\n lis.pop()\n lis.append(c)\n elif c == \'-\':\n if lis and lis[-1] == \',\':\n lis.pop()\n lis.append(c)\n elif c == \',\':\n lis.append(c)\n elif c.isdigit():\n process_digit(lis, c)\n elif c == \']\':\n process_list(lis)\n return lis[0]\n \ndef process_digit(lis, c):\n x = lis[-1]\n c = int(c)\n if x == \'-\':\n lis[-1] = -c\n elif x== \',\':\n lis[-1] = c\n elif x == \'[\':\n lis.append(c)\n elif type(x) is int:\n if x >= 0:\n lis[-1] = 10*x + c\n else:\n lis[-1] = 10*x - c\n\ndef process_list(lis):\n res = []\n while lis[-1] != \'[\':\n res.append(lis.pop())\n lis.pop()\n lis.append(res[::-1])\n \n``` | 1 | 0 | [] | 0 |
mini-parser | Java Straightforward stack solution | java-straightforward-stack-solution-by-p-txer | \nclass Solution {\n public NestedInteger deserialize(String s) {\n Deque<NestedInteger> stack = new ArrayDeque<>();\n int i = 0;\n whil | pandalv9999 | NORMAL | 2019-12-13T19:15:06.622729+00:00 | 2019-12-13T19:15:06.622763+00:00 | 231 | false | ```\nclass Solution {\n public NestedInteger deserialize(String s) {\n Deque<NestedInteger> stack = new ArrayDeque<>();\n int i = 0;\n while (i < s.length()) {\n if (s.charAt(i) == \'[\') {\n stack.push(new NestedInteger());\n i++;\n } else if (s.charAt(i) == \',\') {\n i++;\n } else if (s.charAt(i) == \']\') {\n NestedInteger last = stack.pop();\n if (stack.isEmpty()) {\n return last;\n }\n stack.peek().add(last);\n i++;\n } else { // isDigit or -\n boolean negative = s.charAt(i) == \'-\';\n int count = 0;\n if (negative) {\n i++;\n }\n while (i < s.length() && Character.isDigit(s.charAt(i))) {\n count = count * 10 + s.charAt(i) - \'0\';\n i++;\n }\n if (negative) {\n count = -count;\n }\n if (i >= s.length()) {\n return new NestedInteger(count);\n }\n stack.peek().add(new NestedInteger(count));\n }\n }\n return null;\n }\n}\n\n/*\nif we found [ : push a NestList into stack (isList)\nif we found a number: record down the number (), and add it to list of last element in the stack\nif we found a , : i++\nif we found a ] : push last integer into stack top pop stack top, and add the number to second stack top, or return if stack is empty.\n\n*/\n``` | 1 | 0 | [] | 0 |
mini-parser | recursive solution written in c++ | recursive-solution-written-in-c-by-apeir-0t5b | this problem is very similiar to pasring a boolean expression, so we can use the same method. use a cnt to count the number of parenthesis, and to check whether | apeironc | NORMAL | 2019-10-12T20:11:53.296692+00:00 | 2019-10-12T20:13:17.423661+00:00 | 198 | false | this problem is very similiar to [pasring a boolean expression](https://leetcode.com/problems/parsing-a-boolean-expression/discuss/325228/C%2B%2B-Polish-Notation), so we can use the same method. use a cnt to count the number of parenthesis, and to check whether a coma could split a NestedInteger object\n```\nclass Solution {\npublic:\n NestedInteger deserialize(string s) {\n NestedInteger res;\n \n if(s == "[]"){\n return res;\n }\n \n if(s[0] != \'[\'){\n res.setInteger(stoi(s));\n return res;\n }\n int cnt = 0;\n for(int i = 1, j = 1; i < s.size(); i++){\n if(s[i] == \'[\') cnt++;\n if(s[i] == \']\') cnt--;\n if(i==s.size()-1 || (s[i]==\',\' && cnt==0)){\n res.add(deserialize(s.substr(j, i-j)));\n j = i+1;\n }\n }\n return res;\n \n }\n};\n```\n\n | 1 | 0 | [] | 0 |
mini-parser | simple Java recursive solution | simple-java-recursive-solution-by-sjwang-dtkh | \nclass Solution {\n int i = 0;\n public NestedInteger deserialize(String s) {\n return dfs(s).getList().get(0);\n }\n \n public NestedInt | sjwang0719 | NORMAL | 2019-09-14T17:45:10.371975+00:00 | 2019-09-14T17:45:10.372028+00:00 | 161 | false | ```\nclass Solution {\n int i = 0;\n public NestedInteger deserialize(String s) {\n return dfs(s).getList().get(0);\n }\n \n public NestedInteger dfs(String s) {\n NestedInteger res = new NestedInteger(); \n while (i < s.length()) {\n char c = s.charAt(i);\n if (Character.isDigit(c) || c == \'-\') {\n StringBuilder num = new StringBuilder();\n num.append(c);\n while (i + 1 < s.length() && Character.isDigit(s.charAt(i + 1))) {\n num.append(s.charAt(i + 1));\n i++;\n }\n i++;\n res.add(new NestedInteger(Integer.parseInt(num.toString())));\n } else if (c == \'[\') {\n i = i + 1;\n NestedInteger next = dfs(s);\n res.add(next);\n } else if (c == \']\') {\n i = i + 1;\n break;\n } else {\n i++;\n }\n }\n return res;\n }\n}\n```\n | 1 | 0 | [] | 0 |
mini-parser | Simple Java solution for slow learners like myself with comments (4ms) | simple-java-solution-for-slow-learners-l-rpwo | \nclass Solution {\n public NestedInteger deserialize(String s) {\n if (s == null || "".equals(s)) \n\t\t\treturn null;\n if (!isEnclosed(s)) \ | dumbleeter | NORMAL | 2019-07-22T04:00:21.618656+00:00 | 2019-10-23T05:08:59.832418+00:00 | 289 | false | ```\nclass Solution {\n public NestedInteger deserialize(String s) {\n if (s == null || "".equals(s)) \n\t\t\treturn null;\n if (!isEnclosed(s)) \n\t\t\treturn new NestedInteger(Integer.parseInt(s)); //if not enclosed its number so simply parse out result\n\n NestedInteger root = new NestedInteger();\n s = s.substring(1, s.length() - 1); //strip out outer most layer\n int i = 0;\n while (i < s.length()) {\n //if we encounter comma, skip as this means nothing\n if (s.charAt(i) == \',\') {\n i++;\n continue;\n }\n boolean isNumber = Character.isDigit(s.charAt(i)) || s.charAt(i) == \'-\';\n int end = isNumber ? getNumberEnd(s, i) : getBracketEnd(s, i);\n //if it is number, simply parse the number and add it to the current list\n if (isNumber) \n\t\t\t\troot.add(new NestedInteger(Integer.parseInt(s.substring(i, end))));\n //since we encountered a bracket, find the end of the bracket, and the recursive result to the current list\n else \n\t\t\t\troot.add(deserialize(s.substring(i, end)));\n //advance i to the end as we are done processing the current block\n i = end;\n }\n return root;\n }\n \n private int getBracketEnd(String s, int start) {\n int open = 0, close = 0;\n while (start < s.length()) {\n if (s.charAt(start) == \'[\') \n\t\t\t\topen++;\n else if (s.charAt(start) == \']\') \n\t\t\t\topen--;\n if (open == 0 && close == 0) \n\t\t\t\tbreak; //all the brackets i care about is closed at this point \n start++;\n }\n return start + 1;\n }\n \n private int getNumberEnd(String s, int start) {\n while (start < s.length()) {\n if (s.charAt(start) == \',\') \n\t\t\t\tbreak;\n start++;\n }\n return start;\n }\n \n private boolean isEnclosed(String s) {\n return s.charAt(0) == \'[\';\n }\n}\n``` | 1 | 0 | [] | 1 |
mini-parser | recursive Python solution | recursive-python-solution-by-merciless-4gdm | ```\nclass Solution:\n def deserialize(self, s: str) -> NestedInteger:\n if not s:\n return NestedInteger()\n if s[0] != "[":\n | merciless | NORMAL | 2019-05-14T01:08:59.794543+00:00 | 2019-05-14T01:13:04.016790+00:00 | 244 | false | ```\nclass Solution:\n def deserialize(self, s: str) -> NestedInteger:\n if not s:\n return NestedInteger()\n if s[0] != "[":\n return int(s)\n s,temp,memo,i = s[1:-1], NestedInteger(),"1234567890-",0\n while i < len(s):\n if s[i] in memo:\n d = ""\n while i < len(s) and s[i] in memo:\n d += s[i]\n i += 1\n temp.add(int(d))\n elif s[i] == "[":\n l,r,t = 0,0,""\n while 1:\n t += s[i]\n if s[i] == "[":\n l += 1\n if s[i] == "]":\n r += 1\n if l == r:\n break\n i += 1\n temp.add(self.deserialize(t))\n i += 1\n return temp | 1 | 0 | [] | 0 |
mini-parser | Simple & Fast Python | simple-fast-python-by-autodino-cvb4 | ```\nclass Solution(object):\n def deserialize(self, s):\n """\n :type s: str\n :rtype: NestedInteger\n """\n \n if | autodino | NORMAL | 2018-05-20T15:31:18.795720+00:00 | 2018-05-20T15:31:18.795720+00:00 | 205 | false | ```\nclass Solution(object):\n def deserialize(self, s):\n """\n :type s: str\n :rtype: NestedInteger\n """\n \n if s[0]!=\'[\': return NestedInteger(int(s))\n \n stack=[NestedInteger()]\n num=\'\'\n for i in s:\n if i==\'[\': \n stack.append(NestedInteger())\n elif i==\']\':\n if num:\n stack[-1].add(int(num))\n num=\'\'\n buf=stack.pop()\n stack[-1].add(buf)\n elif i==\',\':\n if num:\n stack[-1].add(int(num))\n num=\'\'\n else:\n num+=i\n \n return stack[0].getList()[0]\n | 1 | 0 | [] | 0 |
mini-parser | Very short and simple Python solution | very-short-and-simple-python-solution-by-sxzs | \nreturn eval(s)\n | bobzhu | NORMAL | 2018-01-20T05:32:43.812000+00:00 | 2018-01-20T05:32:43.812000+00:00 | 167 | false | ```\nreturn eval(s)\n``` | 1 | 0 | [] | 0 |
mini-parser | easy to understand use stack java solution | easy-to-understand-use-stack-java-soluti-a5g7 | ```\npublic NestedInteger deserialize(String s) {\n NestedInteger res = new NestedInteger();\n Stack stack = new Stack();\n for (int i = 0; | willcomeback | NORMAL | 2016-08-15T01:35:42.872000+00:00 | 2016-08-15T01:35:42.872000+00:00 | 363 | false | ```\npublic NestedInteger deserialize(String s) {\n NestedInteger res = new NestedInteger();\n Stack<NestedInteger> stack = new Stack<NestedInteger>();\n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n if (c == '[') {\n stack.push(new NestedInteger());\n continue;\n }\n if (c == ',') {\n continue;\n }\n if (c == ']') {\n NestedInteger temp = stack.pop();\n if (!stack.isEmpty()) {\n stack.peek().add(temp);\n } else {\n stack.push(temp);\n }\n continue;\n }\n int j = i;\n while (j < s.length() && (Character.isDigit(s.charAt(j)) || s.charAt(j) == '-')) {\n j++;\n }\n if (j > i) {\n int num = Integer.parseInt(s.substring(i, j));\n if (!stack.isEmpty()) {\n NestedInteger ni = new NestedInteger(num);\n stack.peek().add(ni);\n } else {\n NestedInteger ni = new NestedInteger(num);\n stack.push(ni);\n }\n i = j - 1;\n }\n }\n return stack.peek();\n } | 1 | 0 | [] | 0 |
mini-parser | Java 10 ms, while loop + recursion (one scan) | java-10-ms-while-loop-recursion-one-scan-7i7g | I found that most of the recursion solutions have to scan through the string s more than once since they find a ',' as a breaking point at each layer in order t | yubad2000 | NORMAL | 2016-08-14T19:15:29.566000+00:00 | 2016-08-14T19:15:29.566000+00:00 | 845 | false | I found that most of the recursion solutions have to scan through the string s more than once since they find a ',' as a breaking point at each layer in order to return a NestedInteger between two ',' or between ',' and ']'. \nMy solution also uses recursion. However, it not only return a NestedInteger but also an index point to the next unseen char. This way, we only need to scan the string s once just like the iterative solution. \n```\npublic class Solution {\n public int helper(char[] cc, int idx, NestedInteger res){\n NestedInteger ret = null; // for storing the list element\n Integer num=null; // for storing the number element\n int sign = 1; // sign of the number\n while ( idx < cc.length && cc[idx] != ']') { // parsing between [ and ]\n char c = cc[idx++];\n if ( c == '[' ) { // start parsing a list by calling helper function\n ret = new NestedInteger();\n idx = helper(cc, idx, ret); // idx is the next index after ]\n } else if ( c == ',' ){ // time to add a element to the list\n if (ret != null) { // it is a List element\n res.add(ret);\n } else { // it is a integer or null\n if (num != null) res.add(new NestedInteger( sign*num ) );\n }\n ret = null; // reset \n num = null;\n sign = 1;\n } else if ( c == '-' ){ // sign of the number\n sign = -1;\n } else { // calculate the number\n num = num == null ? (int)(c-'0'): (num*10) + (int)(c-'0');\n }\n }\n if (ret != null) { // add the last element or the element before ]\n res.add(ret);\n } else {\n if (num != null) res.add(new NestedInteger(sign*num));\n }\n return idx+1; // very important!!! return the next index \n }\n \n public NestedInteger deserialize(String s) {\n NestedInteger ret = new NestedInteger(); // a dummy root element\n helper(s.toCharArray(), 0, ret);\n return ret.getList().get(0); // return a element in the dummy root\n }\n}\n``` | 1 | 0 | [] | 1 |
mini-parser | Python 14-liner iterative solution | python-14-liner-iterative-solution-by-cl-4n1h | \ndef deserialize(self, s):\n stk, num = [NestedInteger()], ''\n for ch in s+' ':\n if ch == '[':\n tmp = NestedInteger()\n s | cloudycandy | NORMAL | 2016-08-17T14:07:41.607000+00:00 | 2016-08-17T14:07:41.607000+00:00 | 262 | false | ```\ndef deserialize(self, s):\n stk, num = [NestedInteger()], ''\n for ch in s+' ':\n if ch == '[':\n tmp = NestedInteger()\n stk[-1].add(tmp)\n stk.append(tmp)\n elif ch in '-01234556789':\n num += ch\n elif num:\n stk[-1].add(NestedInteger(int(num)))\n num = ''\n if ch == ']':\n stk.pop()\n return stk[-1].getList()[0]\n``` | 1 | 0 | [] | 0 |
mini-parser | A very clear and detailed explained iterative solution | a-very-clear-and-detailed-explained-iter-8msh | Iterate through the whole string. Keep a stack to track the NestedInteger objects.\nThe top of the stack is always the current NestedInteger we are working on.\ | ccpromise | NORMAL | 2016-08-23T04:19:27.334000+00:00 | 2016-08-23T04:19:27.334000+00:00 | 309 | false | Iterate through the whole string. Keep a stack to track the NestedInteger objects.\nThe top of the stack is always the current NestedInteger we are working on.\n'[': push a new object into stack\n']': if there are more that one object in the stack, it means the top NestedInteger is an element of the last but one NestedInteger.\n',': just continue\n'0'-'9'\uff1aadd the number to the top NestInteger in stack.\n\nHopefully there are more clean solutions!\n```\npublic class Solution {\n public NestedInteger Deserialize(string s) {\n int i = 0;\n int N = s.Count();\n var objst = new Stack<NestedInteger>();\n \n if(s[0] != '[')\n {\n return new NestedInteger(Convert.ToInt32(s));\n }\n\n while(i < N)\n {\n if(s[i] == '[')\n {\n objst.Push(new NestedInteger());\n i++;\n continue;\n }\n if(s[i] == ',')\n {\n i++;\n continue;\n }\n if(s[i] == ']')\n {\n if(objst.Count()>1)\n {\n var obj = objst.Pop();\n objst.Peek().Add(obj);\n }\n i++;\n continue;\n }\n int n = 0;\n int sign = 1;\n if(s[i] == '-')\n {\n sign = -1;\n i++;\n }\n while(i < N && s[i] >= '0' && s[i] <= '9')\n {\n n = n*10+(s[i] - '0');\n i++;\n }\n objst.Peek().Add(new NestedInteger(sign*n));\n }\n return objst.Peek();\n }\n}\n``` | 1 | 0 | [] | 0 |
mini-parser | my clean solution using one stack | my-clean-solution-using-one-stack-by-hwy-9t4u | \npublic NestedInteger deserialize(String s) {\n if (s == null) {\n return null;\n }\n if (s.charAt(0) != '[') {\n return new NestedInteg | hwy_2015 | NORMAL | 2016-08-24T05:21:38.794000+00:00 | 2016-08-24T05:21:38.794000+00:00 | 225 | false | ```\npublic NestedInteger deserialize(String s) {\n if (s == null) {\n return null;\n }\n if (s.charAt(0) != '[') {\n return new NestedInteger(Integer.valueOf(s));\n }\n NestedInteger nestedInteger = null;\n Stack<NestedInteger> stack = new Stack<NestedInteger>();\n \n for (String elem: s.split(",")) {\n String elem1 = elem.replace("[", "");\n for (int i = 0; i <elem.length() -elem1.length(); i++) {\n stack.push(new NestedInteger());\n } \n String elem2 = elem1.replace("]", "");\n if (elem2.length() > 0) {\n int value = Integer.valueOf(elem2);\n stack.peek().add(new NestedInteger(value));\n } \n for (int i = 0; i < elem1.length() - elem2.length(); i++) {\n nestedInteger = stack.pop();\n if (!stack.isEmpty()) {\n stack.peek().add(nestedInteger);\n }\n }\n }\n \n return nestedInteger;\n}\n``` | 1 | 0 | [] | 0 |
mini-parser | C++ code with 36ms | c-code-with-36ms-by-sanxi-980g | class Solution{\n stack<NestedInteger*> Stack;\n public:\n NestedInteger<string s>{\n NestedInteger *cur;\n | sanxi | NORMAL | 2016-09-06T12:41:22.517000+00:00 | 2016-09-06T12:41:22.517000+00:00 | 394 | false | class Solution{\n stack<NestedInteger*> Stack;\n public:\n NestedInteger<string s>{\n NestedInteger *cur;\n for(int i=0;i<s.size();i++){\n if(s[i]==',')continue;\n cur=new NestedInteger();\n if(s[i]=='[')Stack.push(new NestedInteger());\n else if(s[i]==']'){\n cur=Stack.top();\n Stack.pop();\n if(!Stack.empty())Stack.top()->add(*cur);\n }else{\n int j=i;\n while(j<s.size()&&s[j]!=']'&&s[j]!=',')j++;\n cur->setInteger(stoi(s.substr(i,j-i));\n if(!Stack.empty())Stack.top()->add(*cur);\n i=j-1;\n }\n }\n return Stack.empty()? *cur:*Stack.top();\n }\n }; | 1 | 0 | [] | 0 |
mini-parser | Simple Java Iterative Solution | simple-java-iterative-solution-by-hotpro-rtoq | I like this simple version.\n\n\npublic class Solution {\n\n public NestedInteger deserialize(String s) {\n if (s.charAt(0) != '[') {\n ret | hotpro | NORMAL | 2016-09-28T06:40:59.305000+00:00 | 2016-09-28T06:40:59.305000+00:00 | 310 | false | I like this simple version.\n\n```\npublic class Solution {\n\n public NestedInteger deserialize(String s) {\n if (s.charAt(0) != '[') {\n return new NestedInteger(Integer.parseInt(s));\n }\n Deque<NestedInteger> stack = new LinkedList<>();\n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n if (c == '[') { // start a new NestedInteger\n stack.push(new NestedInteger());\n } else if (c == ']' && stack.size() > 1) { // end, check if need to add curr to upper level\n NestedInteger n = stack.pop();\n stack.peek().add(n);\n } else if (Character.isDigit(c) || c == '-') { // is number, parse it, then add it to upper level\n boolean isNegative = false;\n if (c == '-') {\n isNegative = true;\n i++;\n }\n int num = s.charAt(i) - '0';\n while (i + 1< s.length() && Character.isDigit(s.charAt(i + 1))) {\n num = num * 10 + (s.charAt(i + 1) - '0');\n i++;\n }\n NestedInteger ni = new NestedInteger(isNegative ? -num : num);\n stack.peek().add(ni);\n }\n }\n return stack.pop();\n }\n}\n``` | 1 | 0 | [] | 0 |
mini-parser | Simple and short Java solution | simple-and-short-java-solution-by-ivtosk-s6k1 | \n public NestedInteger deserialize(String s) {\n Stack<NestedInteger> stack = new Stack<>();\n for (int i = 0, num = 0, sign = 1; i < s.length | ivtoskov | NORMAL | 2016-11-02T10:30:37.992000+00:00 | 2016-11-02T10:30:37.992000+00:00 | 281 | false | ```\n public NestedInteger deserialize(String s) {\n Stack<NestedInteger> stack = new Stack<>();\n for (int i = 0, num = 0, sign = 1; i < s.length(); ++i) {\n char c = s.charAt(i);\n if (Character.isDigit(c)) {\n num = num * 10 + c - '0';\n if (i + 1 < s.length() && !Character.isDigit(s.charAt(i + 1))) {\n stack.peek().add(new NestedInteger(num * sign));\n num = 0;\n sign = 1;\n }\n } else if (c == '-') {\n sign = -1;\n } else if (c == '[') {\n stack.push(new NestedInteger());\n } else if (c == ']') {\n NestedInteger current = stack.pop();\n if (stack.isEmpty()) {\n return current;\n } else {\n stack.peek().add(current);\n }\n }\n }\n \n return s.isEmpty() ? new NestedInteger() : new NestedInteger(Integer.parseInt(s));\n }\n``` | 1 | 0 | [] | 0 |
mini-parser | Concise Java Solution | concise-java-solution-by-yavinci-o5hf | The following pattern is very generic for similar questions:\n\n public NestedInteger deserialize(String s) {\n if (s.charAt(0) != '[') {\n | yavinci | NORMAL | 2016-11-09T03:29:33.915000+00:00 | 2016-11-09T03:29:33.915000+00:00 | 391 | false | The following pattern is very generic for similar questions:\n\n public NestedInteger deserialize(String s) {\n if (s.charAt(0) != '[') {\n return new NestedInteger(Integer.valueOf(s));\n }\n\n Deque<NestedInteger> stack = new ArrayDeque<>();\n NestedInteger curr = new NestedInteger();\n \n Integer num = null;\n int sign = 1;\n \n for (char c : s.toCharArray()) {\n if (c == '[') {\n stack.push(curr);\n curr = new NestedInteger();\n \n } else if (c == ',') {\n if (num != null) {\n curr.add(new NestedInteger(sign * num));\n }\n num = null;\n sign = 1;\n \n } else if (c == ']') {\n if (num != null) {\n curr.add(new NestedInteger(sign * num));\n } \n NestedInteger parent = stack.pop();\n parent.add(curr);\n curr = parent;\n \n num = null;\n sign = 1;\n \n } else if (c == '-') {\n sign = -1;\n \n } else {\n if (num == null) {\n num = 0;\n }\n num = num * 10 + c - '0';\n }\n }\n \n return curr.getList().get(0);\n } | 1 | 0 | [] | 0 |
mini-parser | Java 15ms recursive solution beats 88% , short and clean | java-15ms-recursive-solution-beats-88-sh-e7fp | \npublic NestedInteger deserialize(String s) {\n if (s.charAt(0) != '[') return new NestedInteger(Integer.valueOf(s));\n\tNestedInteger res = new NestedI | shawnloatrchen | NORMAL | 2017-01-05T00:53:58.504000+00:00 | 2017-01-05T00:53:58.504000+00:00 | 152 | false | ```\npublic NestedInteger deserialize(String s) {\n if (s.charAt(0) != '[') return new NestedInteger(Integer.valueOf(s));\n\tNestedInteger res = new NestedInteger();\n\tif (s.length() == 2) return res;\n\tint start = 1, end = 1, brackets= 0;\n\tfor (;end < s.length()-1; end++) {\n\t\tchar cur = s.charAt(end);\n\t\tif (cur == '[') brackets++;\n\t\telse if (cur == ']') brackets--;\n\t\telse if (cur == ',' && brackets== 0) {\n\t\t\tres.add(deserialize(s.substring(start, end)));\n\t\t\tstart = end+1;\n\t\t}\n\t}\n\tres.add(deserialize(s.substring(start, end)));\n\treturn res;\n}\n``` | 1 | 0 | [] | 0 |
mini-parser | Java iterative accepted solution using stack | java-iterative-accepted-solution-using-s-d1of | \npublic class Solution {\n public NestedInteger deserialize(String s) {\n NestedInteger ret = new NestedInteger();\n if(s == null || s.isEmpty | gtdoof | NORMAL | 2017-02-02T04:03:26.660000+00:00 | 2017-02-02T04:03:26.660000+00:00 | 521 | false | ```\npublic class Solution {\n public NestedInteger deserialize(String s) {\n NestedInteger ret = new NestedInteger();\n if(s == null || s.isEmpty()) {\n return new NestedInteger();\n }\n \n Stack<NestedInteger> stack = new Stack<>();\n stack.push(ret);\n int sign = 1;\n for(int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n if(c == '[') {\n NestedInteger ni = new NestedInteger();\n if(!stack.isEmpty()) {\n stack.peek().add(ni);\n }\n stack.push(ni);\n sign = 1;\n } else if(Character.isDigit(c)) {\n int num = c - '0';\n while(i+1 < s.length() && Character.isDigit(s.charAt(i+1))) {\n num = num * 10 + s.charAt(i+1) - '0';\n i++;\n }\n num = num * sign;\n sign = 1;\n stack.peek().add(new NestedInteger(num));\n } else if (c == ',') {\n continue;\n } else if (c == ']') {\n stack.pop();\n } else if (c == '-') {\n sign = -1;\n }\n }\n\n return ret.getList().isEmpty() ? ret : ret.getList().get(0);\n }\n}\n``` | 1 | 0 | ['Stack', 'Iterator', 'Java'] | 0 |
maximum-total-damage-with-spell-casting | ✅Beats 100% -Explained with [ Video ] -C++/Java/Python/JS -Dynamic Programming -Interview Solution | beats-100-explained-with-video-cjavapyth-di6s | \n\n\n\n# YouTube Video Explanation:\n\n **If you want a video for this question please write in the comments** \n\nhttps://youtu.be/btt34fYah6s\n\n\n\uD83D\uDD | lancertech6 | NORMAL | 2024-06-16T05:42:16.161957+00:00 | 2024-06-16T07:41:43.289137+00:00 | 8,232 | false | \n\n\n\n# YouTube Video Explanation:\n\n<!-- **If you want a video for this question please write in the comments** -->\n\nhttps://youtu.be/btt34fYah6s\n\n\n**\uD83D\uDD25 Please like, share, and subscribe to support our channel\'s mission of making complex concepts easy to understand.**\n\nSubscribe Link: https://www.youtube.com/@leetlogics/?sub_confirmation=1\n\n*Subscribe Goal: 2000 Subscribers*\n*Current Subscribers: 1976*\n\n---\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires us to maximize the total damage a magician can cast given constraints on which spells can be cast together. Specifically, if a spell with damage `power[i]` is cast, then spells with damages `power[i] - 2`, `power[i] - 1`, `power[i] + 1`, and `power[i] + 2` cannot be cast. This constraint suggests a need for a dynamic programming approach where we keep track of the maximum possible damage while avoiding forbidden spell combinations.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Frequency Count**:\n - Use a `HashMap` to count the frequency of each unique spell damage.\n\n2. **Sort Unique Damages**:\n - Extract unique damage values from the map and sort them. This helps in efficiently checking and updating the dynamic programming state.\n\n3. **Dynamic Programming Array**:\n - Initialize a DP array where `dp[i]` represents the maximum damage achievable using the first `i` unique spell damages.\n - The transition involves either taking the current spell damage (if it doesn\'t conflict with the previously considered spell damages) or skipping it.\n\n4. **State Transition**:\n - For each unique damage, calculate its contribution to the total damage.\n - Update the DP array considering the constraints.\n\n# Complexity\n- **Time Complexity**: \n - Building the frequency map: `O(m)`, where `m` is the number of elements in the input array.\n - Sorting the unique keys: `O(m log m)`.\n - Dynamic programming update: `O(m^2)` in the worst case, due to the nested while loop. However, with efficient indexing, this can be optimized.\n\n- **Space Complexity**: \n - `O(m)` for the frequency map and the DP array.\n\n\n\n# Step By Step Explanation\n\nLet\'s explain the logic using an example with `power = [7, 1, 6, 6]`.\n\n1. **Input Preparation**\n - **Input Array:** `[7, 1, 6, 6]`\n - **Frequency Map:** Count the frequency of each damage value.\n - **Unique Damages:** Extract and sort the unique damage values.\n\n| Element | Count |\n|---------|-------|\n| 1 | 1 |\n| 6 | 2 |\n| 7 | 1 |\n\n- **Unique Damages (sorted):** `[1, 6, 7]`\n- **Frequency:** `{1: 1, 6: 2, 7: 1}`\n\n2. **Initialization**\n - Create a DP array to store the maximum damage up to each unique damage index.\n - **DP Array Initialization:**\n \n| Index | Unique Damage | Frequency | Initial DP Value |\n|-------|---------------|-----------|--------------------------|\n| 0 | 1 | 1 | 1 * 1 = 1 |\n| 1 | 6 | 2 | 0 |\n| 2 | 7 | 1 | 0 |\n\n3. **Dynamic Programming Transition**\n - **Step 1: Processing Damage Value 1**\n\n| i | Current Damage Value | Current Damage Total | Previous Index | Max Damage Up to i | DP Array after Update |\n|----|----------------------|----------------------|----------------|-------------------------|--------------------------|\n| 0 | 1 | 1 * 1 = 1 | - | max(0, 1) = 1 | `[1, 0, 0]` |\n\n - **Step 2: Processing Damage Value 6**\n\n| i | Current Damage Value | Current Damage Total | Previous Index | Max Damage Up to i | DP Array after Update |\n|----|----------------------|----------------------|----------------|-------------------------|--------------------------|\n| 1 | 6 | 6 * 2 = 12 | -1 (no conflict) | max(1, 12) = 12 | `[1, 12, 0]` |\n\n - **Step 3: Processing Damage Value 7**\n\n| i | Current Damage Value | Current Damage Total | Previous Index | Max Damage Up to i | DP Array after Update |\n|----|----------------------|----------------------|----------------|-------------------------|--------------------------|\n| 2 | 7 | 7 * 1 = 7 | 0 (no conflict) | max(12, 1 + 7) = 13 | `[1, 12, 13]` |\n\n4. **Final Result**\n - **Maximum Total Damage:** `13`\n\n### Explanation Summary\n1. **Input Preparation:**\n - Count the frequency of each spell damage.\n - Extract and sort unique damages.\n\n2. **Initialization:**\n - Initialize the DP array with the damage of the first unique spell.\n\n3. **Dynamic Programming Transition:**\n - For each unique damage, calculate its total contribution.\n - Update the DP array by considering conflicts with previous damages.\n\n4. **Result:**\n - The maximum total damage is the last value in the DP array.\n\n\n\n# Code\n```java []\nclass Solution {\n public long maximumTotalDamage(int[] power) {\n // Step 1: Count the frequency of each damage value\n Map<Integer, Long> damageFrequency = new HashMap<>();\n for (int damage : power) {\n damageFrequency.put(damage, damageFrequency.getOrDefault(damage, 0L) + 1);\n }\n\n // Step 2: Extract and sort the unique damage values\n List<Integer> uniqueDamages = new ArrayList<>(damageFrequency.keySet());\n Collections.sort(uniqueDamages);\n\n int totalUniqueDamages = uniqueDamages.size();\n long[] maxDamageDP = new long[totalUniqueDamages];\n\n // Step 3: Initialize the DP array with the first unique damage\n maxDamageDP[0] = uniqueDamages.get(0) * damageFrequency.get(uniqueDamages.get(0));\n\n // Step 4: Fill the DP array with the maximum damage calculations\n for (int i = 1; i < totalUniqueDamages; i++) {\n int currentDamageValue = uniqueDamages.get(i);\n long currentDamageTotal = currentDamageValue * damageFrequency.get(currentDamageValue);\n\n // Initially, consider not taking the current damage\n maxDamageDP[i] = maxDamageDP[i - 1];\n\n // Find the previous damage value that doesn\'t conflict with the current one\n int previousIndex = i - 1;\n while (previousIndex >= 0 && \n (uniqueDamages.get(previousIndex) == currentDamageValue - 1 || \n uniqueDamages.get(previousIndex) == currentDamageValue - 2 || \n uniqueDamages.get(previousIndex) == currentDamageValue + 1 || \n uniqueDamages.get(previousIndex) == currentDamageValue + 2)) {\n previousIndex--;\n }\n\n // Update the DP value considering the current damage\n if (previousIndex >= 0) {\n maxDamageDP[i] = Math.max(maxDamageDP[i], maxDamageDP[previousIndex] + currentDamageTotal);\n } else {\n maxDamageDP[i] = Math.max(maxDamageDP[i], currentDamageTotal);\n }\n }\n\n // Return the maximum damage possible\n return maxDamageDP[totalUniqueDamages - 1];\n }\n}\n\n```\n```C++ []\n#include <vector>\n#include <unordered_map>\n#include <algorithm>\n\nclass Solution {\npublic:\n long long maximumTotalDamage(std::vector<int>& power) {\n std::unordered_map<int, long long> damageFrequency;\n for (int damage : power) {\n damageFrequency[damage]++;\n }\n\n std::vector<int> uniqueDamages;\n for (const auto& pair : damageFrequency) {\n uniqueDamages.push_back(pair.first);\n }\n std::sort(uniqueDamages.begin(), uniqueDamages.end());\n\n int totalUniqueDamages = uniqueDamages.size();\n std::vector<long long> maxDamageDP(totalUniqueDamages, 0);\n\n maxDamageDP[0] = uniqueDamages[0] * damageFrequency[uniqueDamages[0]];\n\n for (int i = 1; i < totalUniqueDamages; i++) {\n int currentDamageValue = uniqueDamages[i];\n long long currentDamageTotal = currentDamageValue * damageFrequency[currentDamageValue];\n\n maxDamageDP[i] = maxDamageDP[i - 1];\n\n int previousIndex = i - 1;\n while (previousIndex >= 0 && \n (uniqueDamages[previousIndex] == currentDamageValue - 1 || \n uniqueDamages[previousIndex] == currentDamageValue - 2 || \n uniqueDamages[previousIndex] == currentDamageValue + 1 || \n uniqueDamages[previousIndex] == currentDamageValue + 2)) {\n previousIndex--;\n }\n\n if (previousIndex >= 0) {\n maxDamageDP[i] = std::max(maxDamageDP[i], maxDamageDP[previousIndex] + currentDamageTotal);\n } else {\n maxDamageDP[i] = std::max(maxDamageDP[i], currentDamageTotal);\n }\n }\n\n return maxDamageDP[totalUniqueDamages - 1];\n }\n};\n```\n```Python []\nclass Solution(object):\n def maximumTotalDamage(self, power):\n damageFrequency = defaultdict(int)\n for damage in power:\n damageFrequency[damage] += 1\n\n uniqueDamages = sorted(damageFrequency.keys())\n totalUniqueDamages = len(uniqueDamages)\n maxDamageDP = [0] * totalUniqueDamages\n\n maxDamageDP[0] = uniqueDamages[0] * damageFrequency[uniqueDamages[0]]\n\n for i in range(1, totalUniqueDamages):\n currentDamageValue = uniqueDamages[i]\n currentDamageTotal = currentDamageValue * damageFrequency[currentDamageValue]\n\n maxDamageDP[i] = maxDamageDP[i - 1]\n\n previousIndex = i - 1\n while (previousIndex >= 0 and \n (uniqueDamages[previousIndex] == currentDamageValue - 1 or \n uniqueDamages[previousIndex] == currentDamageValue - 2 or \n uniqueDamages[previousIndex] == currentDamageValue + 1 or \n uniqueDamages[previousIndex] == currentDamageValue + 2)):\n previousIndex -= 1\n\n if previousIndex >= 0:\n maxDamageDP[i] = max(maxDamageDP[i], maxDamageDP[previousIndex] + currentDamageTotal)\n else:\n maxDamageDP[i] = max(maxDamageDP[i], currentDamageTotal)\n\n return maxDamageDP[totalUniqueDamages - 1]\n\n \n```\n```JavaScript []\nvar maximumTotalDamage = function(power) {\n const damageFrequency = new Map();\n for (let damage of power) {\n damageFrequency.set(damage, (damageFrequency.get(damage) || 0) + 1);\n }\n\n const uniqueDamages = Array.from(damageFrequency.keys()).sort((a, b) => a - b);\n const totalUniqueDamages = uniqueDamages.length;\n const maxDamageDP = Array(totalUniqueDamages).fill(0);\n\n maxDamageDP[0] = uniqueDamages[0] * damageFrequency.get(uniqueDamages[0]);\n\n for (let i = 1; i < totalUniqueDamages; i++) {\n const currentDamageValue = uniqueDamages[i];\n const currentDamageTotal = currentDamageValue * damageFrequency.get(currentDamageValue);\n\n maxDamageDP[i] = maxDamageDP[i - 1];\n\n let previousIndex = i - 1;\n while (previousIndex >= 0 && \n (uniqueDamages[previousIndex] === currentDamageValue - 1 || \n uniqueDamages[previousIndex] === currentDamageValue - 2 || \n uniqueDamages[previousIndex] === currentDamageValue + 1 || \n uniqueDamages[previousIndex] === currentDamageValue + 2)) {\n previousIndex--;\n }\n\n if (previousIndex >= 0) {\n maxDamageDP[i] = Math.max(maxDamageDP[i], maxDamageDP[previousIndex] + currentDamageTotal);\n } else {\n maxDamageDP[i] = Math.max(maxDamageDP[i], currentDamageTotal);\n }\n }\n\n return maxDamageDP[totalUniqueDamages - 1];\n};\n```\n\n\n | 108 | 2 | ['Array', 'Dynamic Programming', 'Python', 'C++', 'Java', 'JavaScript'] | 9 |
maximum-total-damage-with-spell-casting | Catch-Up DP | catch-up-dp-by-votrubac-x2qo | dp[i + 1] represents the best result if i-th spell was casted. \n\nWe sort the array first, so we can easily track all smaller powers we can use when casing i-t | votrubac | NORMAL | 2024-06-16T04:00:52.556056+00:00 | 2024-06-16T18:41:30.838850+00:00 | 4,814 | false | `dp[i + 1]` represents the best result if `i`-th spell was casted. \n\nWe sort the array first, so we can easily track all smaller powers we can use when casing `i`-th spell.\n\nBefore computing `dp[i + 1]`, we "catch up" to include best results for all `power[j]` such as `power[j] + 2 < power[i]`.\n\nWe track the best result for previous spells we can use in `max_dp`, so:\n- `dp[i + 1] = power[i] + max_dp`.\n\t- Again, `max_dp` is `max(dp[0..j + 1])`, where `j` is the largest index such as `power[j] + 2 < power[i]`.\n\nThere is a special case when `power[i] == power[i + 1]`. In this case:\n- `dp[i + 1] = power[i] + dp[i]`.\n\n**Complexity Analysis**\n- Time: O(sort)\n\t- We sort the array, and then go through it once.\n- Memory: O(n)\n\t- We can reduce it to O(1), see the second solution below.\n\n**C++**\n```cpp\nlong long maximumTotalDamage(vector<int>& power) {\n long long dp[100001] = {0}, max_dp = 0;\n sort(begin(power), end(power));\n for (int i = 0, j = 0; i < power.size(); ++i) \n if (power[i] == power[max(0, i - 1)])\n dp[i + 1] = power[i] + dp[i];\n else {\n while(power[j] + 2 < power[i])\n max_dp = max(max_dp, dp[++j]);\n dp[i + 1] = power[i] + max_dp;\n }\n return *max_element(begin(dp), begin(dp) + power.size() + 1);\n}\n```\n\n#### O(1) Memory Complexity\nWe can use deque to track previous best results. \n\nSince we remove elements smaller than `power[i] - 2`, the deque size doesn\'t exceed 3 elements.\n\n**C++**\n```cpp\nlong long maximumTotalDamage(vector<int>& power) {\n deque<array<long long, 2>> dp{{0, 0}};\n long long max_dp = 0;\n sort(begin(power), end(power));\n for (int p : power)\n if (p == dp.back()[1])\n dp.back() = {p + dp.back()[0], p};\n else {\n while(!dp.empty() && dp.front()[1] + 2 < p) {\n max_dp = max(max_dp, dp.front()[0]);\n dp.pop_front();\n }\n dp.push_back({p + max_dp, p});\n }\n return (*max_element(begin(dp), end(dp)))[0];\n}\n``` | 53 | 0 | ['C'] | 9 |
maximum-total-damage-with-spell-casting | 🔥DP || ⚡Memoization || ✅Clean & Easy to understand💯 | dp-memoization-clean-easy-to-understand-xs34p | Complexity\n- Time complexity: O(nlogn)\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 | Sachin___Sen | NORMAL | 2024-06-16T04:07:46.991264+00:00 | 2024-06-16T04:07:46.991289+00:00 | 5,410 | false | # Complexity\n- Time complexity: O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n#define ll long long \nprivate:\n ll getMaxDamage(vector<ll>& dp, map<int, int>& frequencyMap, vector<int>& uniquePowers, int index) {\n if (index == uniquePowers.size()) return 0;\n if (dp[index] != -1) return dp[index];\n // Option 1: Skip the current element\n ll skip = getMaxDamage(dp, frequencyMap, uniquePowers, index + 1);\n // Option 2: Take the current element\n ll take = 0;\n int nextIndex = index + 1;\n while (nextIndex < uniquePowers.size() && uniquePowers[nextIndex] - uniquePowers[index] <= 2) {\n nextIndex++;\n }\n take = ((1ll)*frequencyMap[uniquePowers[index]] * uniquePowers[index]) + getMaxDamage(dp, frequencyMap, uniquePowers, nextIndex);\n return dp[index] = max(take, skip);\n }\npublic:\n long long maximumTotalDamage(vector<int>& power) {\n map<int, int> frequencyMap;\n vector<int> uniquePowers;\n // Create frequency map and unique powers list\n for (auto p : power) {\n frequencyMap[p]++;\n }\n for (auto it : frequencyMap) {\n uniquePowers.push_back(it.first);\n }\n // Initialize DP array with -1\n vector<ll> dp(frequencyMap.size(), -1);\n // Start the recursive function\n return getMaxDamage(dp, frequencyMap, uniquePowers, 0);\n }\n};\n\n``` | 39 | 0 | ['Hash Table', 'Dynamic Programming', 'Memoization', 'C++'] | 6 |
maximum-total-damage-with-spell-casting | [EASIEST] Delete and Earn + Explanation (DP) | easiest-delete-and-earn-explanation-dp-b-i204 | Approach\nThis problem is the same as 740. Delete and Earn, except there\'s one more previous entry that must be skipped\n\nThe logic is basically this: if we t | AlecLC | NORMAL | 2024-06-16T04:08:45.606904+00:00 | 2024-06-17T22:31:50.331880+00:00 | 1,882 | false | # Approach\nThis problem is the same as <b><span style="color:orange">740. Delete and Earn</span></b>, except there\'s one more previous entry that must be skipped\n\nThe logic is basically this: if we take a spell, then we can\'t take any previous spell within 2 of this spell. `dp[i]` is the max strength using only spells up to `spells[i]`. We combine duplicate strengths into a dictionary called `strength` so we can track the benefit of casting a spell.\n\n**Key Intuition**: we don\'t care about disabling +1 and +2 because it\'s redundant. If we only get rid of -1 and -2, cur and cur - 2 will never appear together. So from the perspective of cur - 2, we don\'t need to worry about (cur - 2) + 1 and (cur - 2) + 2 \n\nWe only have to discard previous spells if they\'re within 2. Otherwise, just add the strength of the current spell.\n\n# Code\n```python\nclass Solution:\n # once you cast a spell, disable spells with value -2 to +2\n # this is like delete and earn.\n # - de is -1 to +1: either cur + 2ago or 1ago\n # - this is -2 to +2: either cur + 3ago or 1ago\n def maximumTotalDamage(self, power: List[int]) -> int:\n count = Counter(power)\n strength = {k: k*count[k] for k in count}\n spells = [0, 0, 0] + sorted(list(strength.keys()))\n n = len(spells)\n dp = [0]*n\n for i in range(3, n):\n if spells[i] - spells[i-1] > 2:\n dp[i] = dp[i-1] + strength[spells[i]]\n elif spells[i] - spells[i-2] > 2:\n dp[i] = max(dp[i-1], dp[i-2] + strength[spells[i]])\n else:\n dp[i] = max(dp[i-1], dp[i-3] + strength[spells[i]])\n \n return dp[-1]\n```\n\n# Complexity\n- Time complexity: $O(N \\log N)$\n\n- Space complexity: $O(N)$\n\nYou can make DP space complexity $O(1)$ by only keeping track of 1ago, 2ago and 3ago. But because we need the strength map space would still be $O(N)$ overall (or rather, O(unique elems in power)) | 19 | 0 | ['Dynamic Programming', 'Python3'] | 3 |
maximum-total-damage-with-spell-casting | 6 Approaches | 6-approaches-by-jay_1410-0lsn | 1. TopDown DP\nC++ []\nclass Solution {\npublic:\n vector<long long> DP;\n long long TopDown(int i , int N , vector<array<long long , 2>> &P){\n if | Jay_1410 | NORMAL | 2024-06-16T19:57:14.826689+00:00 | 2024-10-15T10:30:11.528378+00:00 | 1,028 | false | # 1. TopDown DP\n```C++ []\nclass Solution {\npublic:\n vector<long long> DP;\n long long TopDown(int i , int N , vector<array<long long , 2>> &P){\n if(i == N) return 0;\n if(DP[i] != -1) return DP[i];\n long long c1 = TopDown(i + 1 , N , P);\n long long c2 = P[i][1];\n for(int j = i + 1 ; j <= min(N - 1 , i + 3) ; j++){\n if(P[j][0] - P[i][0] > 2){\n c2 += TopDown(j , N , P);\n break;\n }\n }\n return DP[i] = max(c1 , c2);\n }\n long long maximumTotalDamage(vector<int> &power){\n map<int , long long> hashmap;\n for(int num : power) hashmap[num] += num;\n vector<array<long long , 2>> newPowers;\n for(auto &[P , D] : hashmap) newPowers.push_back({P , D});\n int N = newPowers.size();\n DP.resize(N + 1 , -1);\n return TopDown(0 , N , newPowers);\n }\n};\n\n```\n```JAVA []\nclass Solution {\n private long[] DP;\n\n private long TopDown(int i , int N , List<long[]> P){\n if(i == N) return 0;\n if(DP[i] != -1) return DP[i];\n long c1 = TopDown(i + 1, N, P);\n long c2 = P.get(i)[1];\n for (int j = i + 1 ; j <= Math.min(N - 1 , i + 3) ; j++){\n if(P.get(j)[0] - P.get(i)[0] > 2){\n c2 += TopDown(j , N , P);\n break;\n }\n }\n DP[i] = Math.max(c1 , c2);\n return DP[i];\n }\n\n public long maximumTotalDamage(int[] power){\n TreeMap<Integer, Long> hashmap = new TreeMap<>();\n for(int num : power){\n hashmap.put(num , hashmap.getOrDefault(num , 0L) + num);\n } \n\n List<long[]> newPowers = new ArrayList<>();\n for(Map.Entry<Integer, Long> entry : hashmap.entrySet()){\n newPowers.add(new long[]{entry.getKey(), entry.getValue()});\n }\n\n int N = newPowers.size();\n DP = new long[N + 1];\n Arrays.fill(DP , -1);\n return TopDown(0, N, newPowers);\n }\n}\n\n```\n```PYTHON []\nclass Solution:\n def TopDown(self , i , N , P , DP):\n if i == N:\n return 0\n if DP[i] != -1:\n return DP[i]\n c1 = self.TopDown(i + 1, N, P, DP)\n c2 = P[i][1]\n for j in range(i + 1 , min(N - 1 , i + 3) + 1):\n if P[j][0] - P[i][0] > 2:\n c2 += self.TopDown(j , N , P , DP)\n break\n DP[i] = max(c1 , c2)\n return DP[i]\n\n def maximumTotalDamage(self, power):\n hashmap = defaultdict(int)\n for num in power:\n hashmap[num] += num\n\n newPowers = [[P, D] for P, D in sorted(hashmap.items())]\n \n N = len(newPowers)\n DP = [-1] * (N + 1)\n return self.TopDown(0 , N , newPowers, DP)\n\n```\n\n\n\n\n\n\n\n\n\n\n\n# 2. BottomUp DP \n```C++ []\nclass Solution {\npublic:\n long long BottomUP(int N , vector<array<long long , 2>> &P){\n vector<long long> DP(N + 1 , 0);\n for(int i = 0 ; i < N ; i++){\n long long c1 = i ? DP[i - 1] : 0;\n long long c2 = P[i][1];\n for(int j = i - 1 ; j >= max(0 , i - 3) ; j--){\n if(P[i][0] - P[j][0] > 2){\n c2 += DP[j];\n break;\n }\n }\n DP[i] = max(c1 , c2);\n }\n return DP[N - 1];\n }\n long long maximumTotalDamage(vector<int> &power){\n map<int , long long> hashmap;\n for(int num : power) hashmap[num] += num;\n vector<array<long long , 2>> newPowers;\n for(auto &[P , D] : hashmap) newPowers.push_back({P , D});\n return BottomUP(newPowers.size() , newPowers);\n }\n};\n\n```\n```JAVA []\nclass Solution{\n public long BottomUp(int N , List<long[]> P){\n long[] DP = new long[N + 1];\n for (int i = 0 ; i < N ; i++){\n long c1 = i > 0 ? DP[i - 1] : 0;\n long c2 = P.get(i)[1];\n for (int j = i - 1 ; j >= Math.max(0 , i - 3) ; j--) {\n if(P.get(i)[0] - P.get(j)[0] > 2){\n c2 += DP[j];\n break;\n }\n }\n DP[i] = Math.max(c1 , c2);\n }\n return DP[N - 1];\n }\n\n public long maximumTotalDamage(int[] power){\n TreeMap<Integer, Long> hashmap = new TreeMap<>();\n for (int num : power) hashmap.put(num, hashmap.getOrDefault(num, 0L) + num);\n\n List<long[]> newPowers = new ArrayList<>();\n for (Map.Entry<Integer, Long> entry : hashmap.entrySet()){\n newPowers.add(new long[]{entry.getKey(), entry.getValue()});\n }\n\n return BottomUp(newPowers.size(), newPowers);\n }\n}\n```\n```PYTHON []\nclass Solution:\n def BottomUp(self , N , P):\n DP = [0] * (N + 1)\n for i in range(N):\n c1 = DP[i - 1] if i > 0 else 0\n c2 = P[i][1]\n for j in range(i - 1 , max(0 , i - 3) - 1 , -1):\n if P[i][0] - P[j][0] > 2:\n c2 += DP[j]\n break\n DP[i] = max(c1 , c2)\n return DP[N - 1]\n\n def maximumTotalDamage(self , power):\n hashmap = defaultdict(int)\n for num in power : hashmap[num] += num\n\n newPowers = [[P , D] for P , D in sorted(hashmap.items())]\n \n return self.BottomUp(len(newPowers) , newPowers)\n\n```\n\n# 3. Binary Searching The Last State\n```C++ []\nclass Solution {\npublic:\n long long maximumTotalDamage(vector<int> &power){\n map<int , long long> dp;\n for(int p : power) dp[p] += p;\n\n long long maxi = 0 , last = 0;\n\n for(auto &[P , F] : dp){\n auto it = dp.upper_bound(P - 3);\n if(it != dp.begin()) dp[P] += prev(it)->second;\n maxi = max(maxi , dp[P] = last = max(dp[P] , last));\n }\n\n return maxi;\n }\n};\n```\n```JAVA []\nclass Solution {\n public long maximumTotalDamage(int[] power){\n TreeMap<Integer , Long> dp = new TreeMap<>();\n for(int P : power) dp.put(P , dp.getOrDefault(P , 0L) + P);\n\n long maxi = 0 , last = 0;\n\n for(int P : dp.keySet()){\n Map.Entry<Integer , Long> it = dp.floorEntry(P - 3);\n if(it != null) dp.put(P , dp.get(P) + it.getValue());\n dp.put(P, last = Math.max(dp.get(P) , last));\n maxi = Math.max(maxi , last);\n }\n\n return maxi;\n }\n}\n```\n```PYTHON []\nclass Solution:\n def maximumTotalDamage(self, power: List[int]) -> int:\n dp = defaultdict(int)\n for p in power : dp[p] += p\n \n sortedPowers = sorted(dp.keys())\n maxi , last = 0 , 0\n \n for P in sortedPowers:\n id = bisect.bisect_right(sortedPowers , P - 3) - 1\n if id >= 0: dp[P] += dp[sortedPowers[id]]\n dp[P] = last = max(dp[P] , last)\n maxi = max(maxi , last)\n\n return maxi\n```\n\n# 4. Storing Last Three States\n```C++ []\nclass Solution {\npublic:\n long long maximumTotalDamage(vector<int> &power){\n map<int , long long> hashmap;\n for(int p : power) hashmap[p] += p;\n\n // {power , maximumDamage}\n vector<array<long long , 2>> dp(3 , {-1,-1});\n\n long long maxi = 0;\n\n for(auto &[P , F] : hashmap){\n array<long long , 2> newDP = {P , F};\n\n // when we pick this power\n for(int j = 2 ; j >= 0 && dp[j][0] != -1 ; j--){\n if(P - dp[j][0] > 2){\n newDP[1] += dp[j][1];\n break;\n }\n }\n \n // when we do not pick this power\n newDP[1] = max(newDP[1] , dp[2][1]);\n\n // update maximumDamage\n maxi = max(maxi , newDP[1]);\n\n // update dp states\n dp[0] = dp[1];\n dp[1] = dp[2];\n dp[2] = newDP;\n }\n\n return maxi;\n }\n};\n```\n```JAVA []\nclass Solution {\n public long maximumTotalDamage(int[] power){\n TreeMap<Integer , Long> hashmap = new TreeMap<>();\n for(int p : power){\n hashmap.put(p , hashmap.getOrDefault(p , 0L) + p);\n }\n\n // {power, maximumDamage}\n long[][] dp = new long[3][2];\n for(int i = 0 ; i < 3 ; i++){\n dp[i][0] = -1;\n dp[i][1] = -1;\n }\n\n long maxi = 0;\n\n for(Map.Entry<Integer , Long> entry : hashmap.entrySet()){\n int P = entry.getKey();\n long F = entry.getValue();\n long[] newDP = {P , F};\n\n // when we pick this power\n for(int j = 2 ; j >= 0 && dp[j][0] != -1 ; j--){\n if(P - dp[j][0] > 2){\n newDP[1] += dp[j][1];\n break;\n }\n }\n\n // when we do not pick this power\n newDP[1] = Math.max(newDP[1], dp[2][1]);\n\n // update maximumDamage\n maxi = Math.max(maxi , newDP[1]);\n\n // update dp states\n dp[0] = dp[1];\n dp[1] = dp[2];\n dp[2] = newDP;\n }\n\n return maxi;\n }\n}\n\n```\n```PYTHON []\nclass Solution:\n def maximumTotalDamage(self, power: List[int]) -> int:\n hashmap = defaultdict(int)\n for p in power:\n hashmap[p] += p\n\n # {power: maximumDamage}\n dp = [[-1, -1] for _ in range(3)]\n\n maxi = 0\n\n for P , F in sorted(hashmap.items()):\n newDP = [P , F]\n\n # when we pick this power\n for j in range(2 , -1 , -1):\n if dp[j][0] != -1 and P - dp[j][0] > 2:\n newDP[1] += dp[j][1]\n break\n\n # when we do not pick this power\n newDP[1] = max(newDP[1] , dp[2][1])\n\n # update maximumDamage\n maxi = max(maxi , newDP[1])\n\n # update dp states\n dp[0] = dp[1]\n dp[1] = dp[2]\n dp[2] = newDP\n\n return maxi\n```\n# 5. Padding Extra States\n```C++ []\nclass Solution {\npublic:\n long long maximumTotalDamage(vector<int> &power){\n map<int , long long> dp;\n for(int p : power){\n dp[p] += p;\n dp[p - 3] = max(0LL , dp[p - 3]);\n } \n\n long long maxi = 0 , last = 0;\n\n for(auto &[P , F] : dp){\n dp[P] = last = max(dp[P] + dp[P - 3] , last);\n maxi = max(maxi , last);\n }\n\n return maxi;\n }\n};\n\n```\n```JAVA []\nclass Solution {\n public long maximumTotalDamage(int[] power){\n TreeMap<Integer, Long> dp = new TreeMap<>();\n for(int P : power){\n dp.put(P, dp.getOrDefault(P, 0L) + P);\n dp.put(P - 3, Math.max(0L, dp.getOrDefault(P - 3, 0L)));\n }\n \n long maxi = 0 , last = 0;\n \n for(int P : dp.keySet()){\n dp.put(P, last = Math.max(dp.get(P) + dp.getOrDefault(P - 3, 0L), last));\n maxi = Math.max(maxi , last);\n }\n \n return maxi;\n }\n}\n```\n```PYTHON []\nclass Solution:\n def maximumTotalDamage(self, power: List[int]) -> int:\n dp = defaultdict(int)\n for p in power:\n dp[p] += p\n dp[p - 3] = max(0, dp[p - 3])\n\n maxi, last = 0, 0\n\n for p in sorted(dp.keys()):\n dp[p] = last = max(dp[p] + dp[p - 3] , last)\n maxi = max(maxi , last)\n\n return maxi\n```\n\n\n# 6. Compressing The States - \n```C++ []\nclass Solution {\npublic:\n vector<array<long long , 2>> compress(vector<int> &A){\n map<int , long long> mp;\n for(int num : A) mp[num] += num;\n int NP = 1 , LP = 0;\n vector<array<long long , 2>> newA;\n for(auto &[P , D] : mp){\n NP = NP + (LP ? min(3 , P - LP) : 0);\n newA.push_back({NP , D});\n LP = P;\n } \n return newA;\n }\n\n long long maximumTotalDamage(vector<int> &power){\n vector<array<long long , 2>> A = compress(power);\n\n int N = 3 * A.size();\n vector<long long> DP(N + 1 , 0);\n for(array<long long , 2> &PD : A) DP[PD[0]] = PD[1];\n\n for(int P = 1 ; P <= N ; P++){\n if(P >= 3) DP[P] += DP[P - 3];\n DP[P] = max(DP[P] , DP[P - 1]);\n }\n\n return *max_element(DP.begin() , DP.end());\n }\n};\n\n```\n```JAVA []\nclass Solution {\n public List<long[]> compress(int[] A){\n TreeMap<Integer , Long> mp = new TreeMap<>();\n for(int num : A){\n mp.put(num , mp.getOrDefault(num , 0L) + num);\n } \n\n int NP = 1 , LP = 0;\n List<long[]> newA = new ArrayList<>();\n\n for(Map.Entry<Integer, Long> entry : mp.entrySet()){\n int P = entry.getKey();\n long D = entry.getValue();\n NP = NP + (LP != 0 ? Math.min(3 , P - LP) : 0);\n newA.add(new long[]{NP , D});\n LP = P;\n }\n\n return newA;\n }\n\n public long maximumTotalDamage(int[] power) {\n List<long[]> A = compress(power);\n\n int N = 3 * A.size();\n long[] DP = new long[N + 1];\n for (long[] PD : A) DP[(int) PD[0]] = PD[1];\n\n for(int P = 1 ; P <= N ; P++){\n if (P >= 3) DP[P] += DP[P - 3];\n DP[P] = Math.max(DP[P], DP[P - 1]);\n }\n\n long maxElement = 0;\n for(long value : DP){\n maxElement = Math.max(maxElement , value);\n }\n \n return maxElement;\n }\n}\n```\n```PYTHON []\nclass Solution:\n def compress(self, A):\n mp = defaultdict(int)\n for num in A : mp[num] += num\n \n NP , LP = 1 , 0\n newA = []\n\n for P in sorted(mp.keys()):\n NP = NP + (LP if LP == 0 else min(3 , P - LP))\n newA.append([NP, mp[P]])\n LP = P\n \n return newA\n\n def maximumTotalDamage(self , power):\n A = self.compress(power)\n\n N = 3 * len(A)\n DP = [0] * (N + 1)\n for PD in A : DP[PD[0]] = PD[1]\n\n for P in range(1, N + 1):\n if P >= 3 : DP[P] += DP[P - 3]\n DP[P] = max(DP[P], DP[P - 1])\n\n return max(DP)\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n | 13 | 0 | ['Hash Table', 'Binary Search', 'Dynamic Programming', 'Sorting', 'Python', 'C++', 'Java', 'Python3'] | 1 |
maximum-total-damage-with-spell-casting | [Dynamic Programming + Tutorial] Maximum Total Damage With Spell Casting | dynamic-programming-tutorial-maximum-tot-n5mo | Topic : Dynamic Programming\nDynamic Programming is a method used in mathematics and computer science to solve complex problems by breaking them down into simp | never_get_piped | NORMAL | 2024-06-16T04:04:55.591885+00:00 | 2024-06-21T04:50:28.749069+00:00 | 1,909 | false | **Topic** : Dynamic Programming\nDynamic Programming is a method used in mathematics and computer science to solve complex problems by breaking them down into simpler **subproblems**. By solving each subproblem only once and storing the results, it avoids redundant computations, leading to more efficient solutions for a wide range of problems. This article provides a detailed exploration of dynamic programming concepts, illustrated with examples. (GFG)\n\nTo solve dynamic programming problem, we need to answer 2 questions:\n* How to represent each subproblem state.\n* What is the transition from the subproblem to the current problem.\n___\n\n## Solution\nLet\'s firsr rephrase the problem as follow:\n\n```\nGiven an array, find the maximum sum of a subsequence such that the difference between every pair of distinct \nnumbers within the sequence is more than 2.\n```\n\nWe can first sort the array because the original order of numbers is irrelevant to our final answer.\n\n***How to represent each subproblem stat:***\nLet `dp[i]` denote the maximum sum of subsequences where the subsequence ends at `nums[i]`. Since we are focusing on distinct numbers, we can aggregate all occurrences of the same value. Therefore, for each unique number, `i` represents the last index of that number\'s occurrences in the array.\n\n***What is the transition from the subproblem to the current problem.***\nSince each distinct number must have a difference of more than 2 from any other number in the subsequence, and given that our array is already sorted, we can derive the following transition:\n* `dp[i] = max(dp[j] + nums[i] * Count(nums[i]))` where `j < i` and `nums[i] - nums[j] > 2`.\n\n***Optimization:***\nWith the transition described above, the time complexity end up at `O(n ^ 2)`. However, since the index `j` that we consider ranges from `0` to `i - 1`, we can take the maximum of all these numbers and assign it to a variable named `preMax`. Note that the range of `j` should be constrained by the condition that `nums[j] + 2 < nums[i]`. This ensures that the difference between `nums[i]` and `nums[j]` is more than 2.\n\n\n## Code\n<iframe src="https://leetcode.com/playground/exXX9wU3/shared" frameBorder="0" width="800" height="300"></iframe>\n\n**Complexity**:\n* Time Complexity : `O(n log n)`\n* Space Complexity : `O(n)`\n\n**Feel free to leave a comment if something is confusing, or if you have any suggestions on how I can improve the post.** | 12 | 1 | ['C', 'PHP', 'Python', 'Java', 'Go', 'JavaScript'] | 2 |
maximum-total-damage-with-spell-casting | ⚡Using DP || 🔥Memoization || ✅Clean Code | using-dp-memoization-clean-code-by-adish-0fn7 | \n# Complexity\n\n- Time complexity:\nO(nlogn)\n\n- Space complexity:\nO(n)\n\n\n## Connect with me on LinkedIn : https://www.linkedin.com/in/aditya-jhunjhunwal | aDish_21 | NORMAL | 2024-06-16T04:04:33.467357+00:00 | 2024-06-16T12:05:47.904770+00:00 | 2,363 | false | \n# Complexity\n```\n- Time complexity:\nO(nlogn)\n\n- Space complexity:\nO(n)\n```\n\n## Connect with me on LinkedIn : https://www.linkedin.com/in/aditya-jhunjhunwala-51b586195/\n\n# Code\n## Please Upvote if it helps\uD83E\uDD17\n```\nclass Solution {\npublic:\n unordered_map<int, int> mp;\n vector<long long> dp;\n vector<int> nextIndex;\n \n long long helper(int ind, int n, vector<int>& power) {\n if (ind >= n)\n return 0;\n if (dp[ind] != -1)\n return dp[ind];\n \n long long maxi = 0;\n if (nextIndex[ind] < n)\n maxi = mp[power[ind]] * (long long)power[ind] + helper(nextIndex[ind], n, power);\n else\n maxi = mp[power[ind]] * (long long)power[ind];\n \n maxi = max(maxi, helper(ind + mp[power[ind]], n, power));\n return dp[ind] = maxi;\n }\n \n long long maximumTotalDamage(vector<int>& power) {\n int n = power.size();\n for (auto it : power)\n mp[it]++;\n sort(power.begin(), power.end());\n\n // Precompute the next valid index for each index\n nextIndex.resize(n, n); // Default to n (out of bounds)\n for (int i = 0; i < n; ++i) {\n int newInd = upper_bound(power.begin() + i + 1, power.end(), power[i] + 2) - power.begin();\n nextIndex[i] = newInd;\n }\n\n dp.resize(n, -1);\n return helper(0, n, power);\n }\n};\n``` | 10 | 0 | ['Dynamic Programming', 'Memoization', 'C++'] | 4 |
maximum-total-damage-with-spell-casting | C++||Tabulation||memoization||Dp+Binary Search | ctabulationmemoizationdpbinary-search-by-n0hl | 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 | baibhavkr143 | NORMAL | 2024-06-16T04:02:29.198590+00:00 | 2024-06-16T04:15:22.206010+00:00 | 2,490 | 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\nMemoization code ->\n**It will give TLE i dont know why **\n```\nclass Solution {\npublic:\n vector<int> uniquePower;\n vector<long long> dp;\n long long fn(int ind, vector<pair<int, long long>>& arr) {\n if (ind >= arr.size())\n return 0;\n if (dp[ind] != -1)\n return dp[ind];\n\n long long nonPick = fn(ind + 1, arr);\n\n int targetInd = lower_bound(uniquePower.begin(), uniquePower.end(),\n uniquePower[ind] + 3) -\n uniquePower.begin();\n\n long long pick =\n (0ll + arr[ind].first * arr[ind].second + fn(targetInd, arr));\n\n return dp[ind] = max(pick, nonPick);\n }\n long long maximumTotalDamage(vector<int>& power) {\n vector<pair<int, long long>> arr;\n map<int, long long> mp;\n for (auto it : power)\n mp[it]++;\n for (auto it : mp) {\n arr.push_back({it.first, it.second});\n uniquePower.push_back(it.first);\n }\n dp.resize(arr.size() + 1, -1);\n return fn(0, arr);\n }\n};\n```\n\n\n\nTabulation code ->\n```\nclass Solution {\npublic:\n vector<int>uniquePower;\n vector<long long>dp;\n long long maximumTotalDamage(vector<int>& power) {\n vector<pair<int,long long>>arr;\n map<int,long long>mp;\n for(auto it:power)mp[it]++;\n for(auto it:mp){\n arr.push_back({it.first,it.second});\n uniquePower.push_back(it.first);\n }\n //Tabulation \n dp.resize(arr.size()+1,0);\n int n=arr.size();\n dp[n-1]=arr[n-1].first*arr[n-1].second;\n dp[n]=0;\n for(int i=n-2;i>=0;i--)\n {\n int targetInd=lower_bound(uniquePower.begin(),uniquePower.end(),uniquePower[i]+3)-uniquePower.begin();\n long long pick=(long long)arr[i].first*arr[i].second+dp[targetInd];\n long long nonPick=dp[i+1];\n dp[i]=max(pick,nonPick);\n }\n \n return dp[0];\n \n }\n};\n``` | 10 | 1 | ['C++'] | 4 |
maximum-total-damage-with-spell-casting | Dynamic Programming solution || [Sort + Optimized O(n) DP] || Python, C++ | dynamic-programming-solution-sort-optimi-8c5g | Intuition\nIt\'s a straightforward Dynamic Programming problem, with 2 main points to note:\n1. DP based on the power level: \nGives the intuition that the orde | ayradnuos | NORMAL | 2024-06-16T04:47:01.072305+00:00 | 2024-06-16T06:47:05.476828+00:00 | 671 | false | # Intuition\nIt\'s a straightforward Dynamic Programming problem, with 2 main points to note:\n1. DP based on the power level: \nGives the intuition that the order of power needs to be maintained and hence, a good starting point would be to sort the powers.\n2. Multiple spells with the same power level:\nThe definition of compatible spells indicate that there\'s nothing against using multiple spells of the same power level.\n - Therefore, a key thing to note is, if a spell of a certain power level is chosen, then the optimal answer will include all the spells of that power level.\n - Moreover, currently the number of entries (/spells) we would have to go through in our sorted spell list before we reach our previous compatible spell (i.e., spells with power < current spell power - 2) is $$O(n)$$. Since, we would need to iterate backwards and find the last compatible spell for every spell, our DP approach would end up with a complexity of $$O(n^2)$$.\n - To optimize this, we could group all the spells of the same power level and just keep track of the count. This would simplify our approach and bring down the complexity of the DP algorithm (excluding the sort) to $$O(n)$$. (For more details on the complexity, look below.)\n\n---\n\n\n# Approach\n`This is a very simplified approach of the given intuition.`\n`Optimizations and suggestions are more than welcome.`\n\n- Keep track of the number of spells that belong to each power level. We can do this by using a dictionary. \n- Sort the power levels of the spells (i.e., the keys of the dictionary).\n- We now formulate our core DP logic:\n```\n# The damage that can be dealt by all the spells in this power level\ncurr_damage = sorted_power[i] * spell_count[sorted_power[i]]\ndp[i] = max(\n # Including current power level\n prev_best + curr_damage,\n # Excluding current power level\n dp[i - 1]\n )\n\n# Here, prev_best is the most damage that could be dealt up until the\n# previous compatible spell. By definition, a spell is compatible \n# if its power level is < current power level - 2.\n\n```\n\n\n---\n\n\n# Code\n```python []\nclass Solution:\n def maximumTotalDamage(self, power: List[int]) -> int:\n # Keep track of the number of spells belonging to each \n # power level\n spell_count = {}\n for p in power:\n spell_count[p] = spell_count.get(p, 0) + 1\n\n sorted_power = sorted(spell_count.keys())\n dp = [0] * len(sorted_power)\n\n for i in range(len(sorted_power)):\n prev_best = 0\n\n # Find the previous compatible spell and the \n # maximum damage that could be dealt up until that level.\n \n j = i - 1\n while j >= 0 and sorted_power[j] >= sorted_power[i] - 2:\n j -= 1\n if j >= 0:\n prev_best = dp[j]\n\n # Calculates the most damage that could be dealt up \n # until this point as the maximum of damage including \n # this power level and excluding.\n\n dp[i] = max(prev_best + sorted_power[i] * spell_count[sorted_power[i]], dp[i-1])\n\n return dp[-1]\n```\n```C++ []\n#include <algorithm>\n#include <unordered_map>\n\nclass Solution {\npublic:\n long long maximumTotalDamage(vector<int>& power) {\n std::unordered_map<int, int> spell_count;\n std::vector<int> power_levels;\n\n for (int p : power) {\n if (spell_count.find(p) != spell_count.end()){\n spell_count[p] += 1;\n } else {\n spell_count[p] = 1;\n power_levels.push_back(p);\n }\n }\n\n std::sort(power_levels.begin(), power_levels.end());\n long long* dp = new long long[power_levels.size()];\n\n for (int i = 0; i < power_levels.size(); ++i) {\n int j = i - 1;\n long long prev_best = 0;\n while(j >= 0 && power_levels[j] >= power_levels[i]-2){\n j--;\n }\n if(j >= 0)\n prev_best = dp[j];\n if(i == 0)\n dp[i] = (long long)power_levels[i] * spell_count[power_levels[i]];\n else\n dp[i] = std::max(prev_best + (long long)((long long)power_levels[i] * spell_count[power_levels[i]]), dp[i-1]);\n }\n \n return dp[power_levels.size()-1];\n }\n};\n```\n\n---\n\n\n# Complexity\nLet $$n$$ be the length of the spell list.\n\n- Time complexity: $$O(nlogn)$$\nThere are three main components to our approach.\n - Counting the number of spells for each power level:\n For this we go through the entire spell list once, and keep updating a dictionary. The dictionary updates are $$O(1)$$. Therefore, this step has a complexity of $$O(n)$$.\n - Sorting the power levels: \n Since $$ #power\\_levels \\le #spells $$, this step has a worst-case complexity of $$O(nlogn)$$.\n - Finally, our core DP logic:\nWe iterate through the sorted power_level list ($$O(n)$$) and for each power_level, we find the last compatible power_level. Since, we grouped all spells of the same power levels, we only have unique values in this list. Therefore, our backward search can only have a maximum of two potential misses before finding a compatible spell. Leaving us with a $$O(n)$$ DP approach.\n\n Overall, sorting takes the biggest chunk of our time complexity and makes our approach $$O(nlogn)$$.\n\n- Space complexity: $$O(n)$$\nWe use two additional data structures\n - $$spell\\_count$$ dictionary: In the worst case, if all spells are of unique power levels, then the dictionary would be of size $$O(n)$$.\n - $$dp$$ array: In the worst case, if all spells are of unique power levels, then the dictionary would be of size $$O(n)$$.\n | 8 | 0 | ['Dynamic Programming', 'Sorting', 'C++', 'Python3'] | 3 |
maximum-total-damage-with-spell-casting | Dynamic Programming Approach || Sorting || Beats 100% in Space and Time || Easy Explaination || C++ | dynamic-programming-approach-sorting-bea-mp8e | \n\n# Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem requires finding the maximum total damage that can be achieved by eit | CS_2201640100272 | NORMAL | 2024-06-16T16:37:51.781004+00:00 | 2024-06-22T05:19:07.463406+00:00 | 350 | false | \n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires finding the maximum total damage that can be achieved by either casting or not casting spells based on given power values.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Sort the Power Array:** This ensures spells are processed in non-decreasing order.\n2. **Dynamic Programming with Memoization:** Use a recursive function with memoization to store the maximum damage achievable from any given index onward.\n\n3. **Decision Making:**\n- **Not Take:** Skip all occurrences of the current power and move to the next distinct power.\n- **Take:** Consider all occurrences of the current power and jump to the first power greater than the current power plus 2.\n\n# Complexity\n## Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n- **Sorting**: Sorting the power array takes O(n log n)\\.\n\n- **Recursive Function**:\n - For each unique element in the power array, the recursive function processes all its occurrences.\n - Let\'s denote the number of unique elements by \\(u\\).\n - On average, each call to `f1` processes average of \\(n/u\\) elements.\n - Thus, the overall complexity for the recursive calls is \\(O(u) \\. O(n/u) = O(n)\\).\n\nCombining these, the overall time complexity is \\(O(n log n) + O(n)\\), which simplifies to O(n log n).\n\n## Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n- **DP Array:** The `dp` array requires \\(O(n)\\) space.\n- **Recursion Stack:** The depth of the recursion stack can go up to \\(O(n)\\) in the worst case.\n\nThus, the overall space complexity is O(n).\n\n# Code\n```\nclass Solution {\n int n = 0;\n vector<long long> dp;\n long long f1(int i, vector<int>& power) {\n if (i == n) \n return 0;\n if (dp[i] != -1) return dp[i];\n long long take = 0, notTake = 0;\n int j = i + 1, count = 1;\n while (j < n && power[j] <= power[i]+2) {\n if (power[j] == power[i]) \n count++;\n j++;\n }\n notTake = f1(i + count, power);\n // j stores the index of first element greater than nums[i] + 2.\n take = (long long)power[i] * count + f1(j, power);\n return dp[i] = max(take, notTake);\n }\npublic:\n long long maximumTotalDamage(vector<int>& power) {\n sort(power.begin(), power.end());\n n = power.size();\n dp.resize(n, -1);\n return f1(0, power);\n }\n};\n``` | 6 | 0 | ['Dynamic Programming', 'Greedy', 'Sorting', 'C++'] | 2 |
maximum-total-damage-with-spell-casting | Sorting+Recursive DP->iteration||148ms Beats 100% | sortingrecursive-dp-iteration148ms-beats-fsy4 | Intuition\n Describe your first thoughts on how to solve this problem. \nUse recursion+ memo to solve. 1d recursive DP\nUse take or not take argument.\n\n2nd C+ | anwendeng | NORMAL | 2024-06-16T07:18:20.420321+00:00 | 2024-06-16T13:01:42.560641+00:00 | 921 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse recursion+ memo to solve. 1d recursive DP\nUse take or not take argument.\n\n2nd C++ is a conversion of recursive DP to an iterative DP.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. sort the `power`\n2. Build an array `spell` over the infor pair `(power, damage)`. Note same power `x` can be perform `fr` times (for freq `fr`) with damage `x*fr`.\n3. Define a recursive `f` with memo `dp`; using take or not take arguement to implement.\n4. the answer is `f(0, spell)`\n5. 2nd C++ is an iterative DP\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n\\log n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n# Code Sorting+Recursive DP||190ms Beats 100%\n```\nclass Solution {\npublic:\n using info=pair<int, long long>;// (power, damage)\n long long dp[100001];\n int sz;\n long long f(int i, vector<info>& spell){\n if (i>=sz) return 0;\n if (dp[i]!=-1) return dp[i];\n\n long long notake=f(i+1, spell);\n\n long long take=0;\n int j=i+1, x=spell[i].first;\n for(; j<sz && spell[j].first<=x+2; j++);\n\n take=spell[i].second+f(j, spell);\n \n return dp[i]=max(take, notake);\n }\n\n long long maximumTotalDamage(vector<int>& power) {\n const int n=power.size();\n sort(power.begin(), power.end());\n\n vector<info> spell={{power[0], power[0]}};\n for(int i=1; i<n; i++){\n int x=power[i]; \n if (x!=power[i-1]) spell.emplace_back(x, (long long)x);\n else spell.back().second+=x;\n }\n sz=spell.size();\n\n fill(dp, dp+sz, -1);\n return f(0, spell);\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# C++ iterative DP||148ms Beats 100%\n```\nclass Solution {\npublic:\n using info=pair<int, long long>;// (power, damage)\n static long long maximumTotalDamage(vector<int>& power) {\n const int n=power.size();\n sort(power.begin(), power.end());\n\n vector<info> spell={{power[0], power[0]}};\n for(int i=1; i<n; i++){\n int x=power[i]; \n if (x!=power[i-1]) spell.emplace_back(x, (long long)x);\n else spell.back().second+=x;\n }\n int sz=spell.size();\n vector<long long> dp(sz+1, 0);\n\n for(int i=sz-1; i>=0; i--){\n long long notake=dp[i+1];\n long long take=0;\n int j=i+1, x=spell[i].first;\n for(; j<sz && spell[j].first<=x+2; j++);\n\n take=spell[i].second+dp[j];\n dp[i]=max(take, notake);\n }\n \n return dp[0];\n }\n};\n\nauto init = []() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n return \'c\';\n}();\n``` | 6 | 0 | ['Dynamic Programming', 'Sorting', 'C++'] | 1 |
maximum-total-damage-with-spell-casting | DP & Sorting | Either take every occurrence of a num or none | dp-sorting-either-take-every-occurrence-i8o4x | \nclass Solution {\n private Long[] memo = null;\n \n private long dfs(int i, int[] A) {\n int n = A.length;\n if(i >= n) return 0;\n | ved72 | NORMAL | 2024-06-16T08:31:38.381625+00:00 | 2024-06-16T08:32:21.221181+00:00 | 496 | false | ```\nclass Solution {\n private Long[] memo = null;\n \n private long dfs(int i, int[] A) {\n int n = A.length;\n if(i >= n) return 0;\n \n if(memo[i] != null) return memo[i];\n \n long take = 0, skip = 0;\n \n //we will either take every occurrence of a number or none\n int firstOcc = i, lastOcc = i;\n while(lastOcc < n && A[lastOcc] == A[firstOcc]) lastOcc++;\n lastOcc--;\n \n skip = dfs(lastOcc + 1, A);\n \n int j = lastOcc + 1;\n while(j < n && A[j] <= A[firstOcc] + 2) j++;\n \n take = (lastOcc - firstOcc + 1) * (long)A[firstOcc] + dfs(j, A);\n return memo[i] = Math.max(take, skip);\n }\n \n public long maximumTotalDamage(int[] A) {\n Arrays.sort(A);\n memo = new Long[A.length];\n return dfs(0, A);\n }\n}\n``` | 5 | 0 | ['Dynamic Programming', 'Recursion', 'Memoization', 'Sorting', 'Java'] | 1 |
maximum-total-damage-with-spell-casting | MEMO 📝 + TABULATION 📊 + SPACE OPTIMIZATION 🚀 + C++ 🖥️ 100% | memo-tabulation-space-optimization-c-100-tfed | Problem Explanation\nYou are given an array power, where each element represents the damage of a spell. The goal is to determine the maximum possible total dama | LaxmanSinghBisht | NORMAL | 2024-06-16T04:14:34.709753+00:00 | 2024-06-16T06:14:43.781555+00:00 | 650 | false | ### Problem Explanation\nYou are given an array `power`, where each element represents the damage of a spell. The goal is to determine the maximum possible total damage a magician can achieve under certain constraints:\n- If a spell with damage `power[i]` is cast, spells with damages `power[i] - 2`, `power[i] - 1`, `power[i] + 1`, or `power[i] + 2` cannot be cast.\n- Each spell can only be cast once.\n\n### Intuition\nTo solve this problem, we can use a dynamic programming (DP) approach:\n1. **Dynamic Programming Setup**: Use a recursive function (`dpHelp`) that computes the maximum damage achievable up to a given index `idx`.\n2. **Memoization**: Use a `dp` array to store already computed results to avoid redundant computations.\n\n### Approach\n#### `dpHelp` Function\n- **Base Case**: If `idx < 0`, return 0 (no more spells to consider).\n- **Memoization Check**: If `dp[idx]` is already computed, return it.\n- **Calculate `notPick`**: This represents the maximum damage achievable without picking the current spell `idx`.\n- **Calculate `pick`**: This represents the maximum damage achievable by picking the current spell `idx` (`power[idx] * count[power[idx]]`).\n- **Handling Constraints**:\n - If the current spell `power[idx]` is consecutive to the previous one (`power[idx] == power[idx - 1] + 1`):\n - Check if skipping two spells back (`idx - 2`) is possible (`power[idx] == power[idx - 2] + 2`). If so, add the corresponding damage.\n - If not consecutive or if skipping two spells back is not possible, skip only one spell back (`idx - 1`).\n- **Store and Return**: Store the maximum of `pick` and `notPick` in `dp[idx]` and return it.\n\n#### `maximumTotalDamage` Function\n- **Count Frequencies**: Use an unordered map to count the frequencies of each spell\'s damage.\n- **Extract Unique Powers**: Extract unique spell damages from the map and sort them.\n- **Initialize DP Array**: Initialize a `dp` array with `-1` to indicate that results haven\'t been computed yet.\n- **Call `dpHelp`**: Call the `dpHelp` function with the sorted unique powers, starting from the last index (`n - 1`).\n- **Return Result**: Return the result computed by `dpHelp`, which represents the maximum possible total damage.\n\n### Complexity Analysis\n- **Time Complexity**:\n - Sorting the unique powers takes `O(n log n)`.\n - Each recursive call in `dpHelp` processes in constant time after memoization, resulting in `O(n)` for the recursion with memoization.\n - Overall time complexity is dominated by sorting, `O(n log n)`.\n\n- **Space Complexity**:\n - `O(n)` for the `dp` array.\n - Additional space for counting frequencies and storing unique powers.\n - Overall space complexity is `O(n)`.\n\n### Complete Code\n\n##### MEMO\n```cpp\nclass Solution {\nprivate:\n long long dpHelp(vector<int>& power, unordered_map<int, long long>& count, int idx, vector<long long>& dp) {\n if (idx < 0) return 0;\n if (dp[idx] != -1) return dp[idx];\n \n long long notPick = dpHelp(power, count, idx - 1, dp); // Maximum damage without picking the current index\n \n long long pick = power[idx] * count[power[idx]]; // Maximum damage by picking the current index\n \n // Check conditions for picking previous powers\n if (idx >= 1 && power[idx] == power[idx - 1] + 1) {\n // If current power is consecutive to the previous one, decide to skip one or two indices back\n if (idx >= 2 && power[idx] == power[idx - 2] + 2) {\n pick += dpHelp(power, count, idx - 3, dp); // Skip two indices back\n } else {\n pick += dpHelp(power, count, idx - 2, dp); // Skip one index back\n }\n } else {\n // Otherwise, skip one index back\n if (idx > 0 && power[idx] == power[idx - 1] + 2) {\n pick += dpHelp(power, count, idx - 2, dp); // Skip one index back\n } else {\n pick += dpHelp(power, count, idx - 1, dp); // Do not skip\n }\n }\n \n // Store and return the maximum of picking or not picking the current index\n return dp[idx] = max(pick, notPick);\n }\n \npublic:\n long long maximumTotalDamage(vector<int>& power) {\n unordered_map<int, long long> count;\n \n // Count frequencies of each power\n for (auto it : power) {\n count[it]++;\n }\n \n // Extract unique powers and sort them\n vector<int> p;\n for (auto it : count) {\n p.push_back(it.first);\n }\n sort(p.begin(), p.end());\n \n // Initialize dp array with -1\n int n = p.size();\n vector<long long> dp(n, -1);\n \n // Call the dpHelp function with the sorted unique powers\n return dpHelp(p, count, n - 1, dp);\n }\n};\n```\n\n#### Tabulation \n\n```\nclass Solution {\n\npublic:\n long long maximumTotalDamage(vector<int>& p) {\n unordered_map<int,long long>count;\n vector<int>power;\n for(auto it:p)\n count[it]++;\n\n for(auto it:count)\n power.push_back(it.first);\n\n sort(power.begin(),power.end());\n int n=power.size();\n vector<long long>dp(n+1,0);\n for(int idx=1;idx<=n;idx++){\n long long notPick=dp[idx-1];\n long long pick=power[idx-1]*count[power[idx-1]];\n if(idx>=2 && power[idx-1]==power[idx-2]+1){\n if(idx>=3&&power[idx-1]==power[idx-3]+2)\n pick+=dp[idx-3];\n else \n pick+=dp[idx-2];\n }\n else{\n if(idx>1&&power[idx-1]==power[idx-2]+2)\n pick+=dp[idx-2];\n else \n pick+=dp[idx-1];\n }\n dp[idx]=max(pick,notPick);\n }\n return dp[n];\n }\n};\n\n```\n\n#### Space Optimziation \n```\nclass Solution {\n\npublic:\n long long maximumTotalDamage(vector<int>& p) {\n unordered_map<int,long long>count;\n vector<int>power;\n for(auto it:p)\n count[it]++;\n\n for(auto it:count)\n power.push_back(it.first);\n\n sort(power.begin(),power.end());\n int n=power.size();\n vector<long long>dp(3,0);\n for(int idx=1;idx<=n;idx++){\n long long notPick=dp[(idx-1)%3];\n long long pick=power[idx-1]*count[power[idx-1]];\n if(idx>=2 && power[idx-1]==power[idx-2]+1){\n if(idx>=3&&power[idx-1]==power[idx-3]+2)\n pick+=dp[(idx-3)%3];\n else \n pick+=dp[(idx-2)%3];\n }\n else{\n if(idx>1&&power[idx-1]==power[idx-2]+2)\n pick+=dp[(idx-2)%3];\n else \n pick+=dp[(idx-1)%3];\n }\n dp[idx%3]=max(pick,notPick);\n }\n return dp[n%3];\n }\n};\n``` | 5 | 0 | ['C++'] | 3 |
maximum-total-damage-with-spell-casting | DP+Sorting+Map | dpsortingmap-by-ayushnemmaniwar12-d21z | Code\n\nclass Solution {\npublic:\n long long maximumTotalDamage(vector<int>& v) {\n map<long long,long long>m;\n for(auto i:v)\n m[ | ayushnemmaniwar12 | NORMAL | 2024-06-16T04:06:52.955790+00:00 | 2024-06-16T04:06:52.955817+00:00 | 1,284 | false | # Code\n```\nclass Solution {\npublic:\n long long maximumTotalDamage(vector<int>& v) {\n map<long long,long long>m;\n for(auto i:v)\n m[i]++;\n vector<pair<int,long long>>temp;\n for(auto i:m) {\n long long k=i.first*i.second;\n temp.push_back({i.first,k});\n }\n int n=temp.size();\n vector<long long>dp(n,0);\n dp[0]=temp[0].second;\n long long ans=dp[0];\n for(int i=1;i<n;i++) {\n int j=i-1,c=8;\n long long k=0;\n while(j>=0 && c>=0) {\n if(temp[j].first+2<temp[i].first) {\n k=max(k,dp[j]);\n }\n j--;\n c--;\n }\n dp[i]=temp[i].second+k;\n ans=max(ans,dp[i]);\n }\n return ans;\n }\n};\n``` | 5 | 0 | ['Dynamic Programming', 'Ordered Map', 'C++'] | 2 |
maximum-total-damage-with-spell-casting | House robber | house-robber-by-dekail-a6dp | Intuition\nSimilar to LC 198 LC 740\n\n\n# Complexity\n- Time complexity:\nO(nlogn)\n\n- Space complexity:\nO(n)\n\n# Code\n\nclass Solution:\n def maximumTo | dekail | NORMAL | 2024-06-16T04:01:20.827398+00:00 | 2024-06-16T05:08:52.801824+00:00 | 578 | false | # Intuition\nSimilar to [LC 198](https://leetcode.com/problems/house-robber/) [LC 740](https://leetcode.com/problems/delete-and-earn/description/)\n\n\n# Complexity\n- Time complexity:\n$$O(nlogn)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nclass Solution:\n def maximumTotalDamage(self, power: List[int]) -> int:\n # group the spells by the same values\n count = Counter(power)\n nums = sorted(count.keys())\n n = len(nums)\n\n # only 1 unique number, return the sum\n if n == 1:\n return sum(power)\n \n # dp[i]: the maximum damage that using nums[:i] spells\n dp = [0 for _ in range(n+1)]\n dp[1] = count[nums[0]] * nums[0]\n\n # if spell nums[0] < spell nums[1] - 2\n # we can use both of them\n if nums[1] - 2 > nums[0]:\n dp[2] = count[nums[1]] * nums[1] + dp[1]\n\n # otherwise, we use the larger one\n else:\n dp[2] = max(count[nums[1]] * nums[1], dp[1])\n\n for i in range(3, n+1):\n num = nums[i - 1]\n # if spell nums[i - 2] < spell nums[i - 1] - 2\n # we can use both of them\n if nums[i - 2] < num - 2:\n dp[i] = dp[i - 1] + count[num] * num\n\n # otherwise, we select the larger one: \n # using spell nums[i - 2]\n # using spell nums[i - 1] and spell nums[i - 3] \n # (spell nums[i - 3] is < spell nums[i - 1] - 2)\n elif nums[i - 2] == num - 2:\n dp[i] = max(dp[i - 1], dp[i - 2] + count[num] * num)\n\n # if spell nums[i - 2] == spell nums[i - 1] - 1\n elif nums[i - 2] == num - 1:\n # if spell nums[i - 3] == spell nums[i - 1] - 2\n # we select the larger one:\n # using spell nums[i - 2]\n # using spell nums[i - 3]\n # using spell nums[i - 1] and spell nums[i - 4]\n # (spell nums[i - 4] is < spell nums[i - 1] - 2)\n if nums[i - 3] == num - 2:\n dp[i] = max(dp[i - 1], dp[i - 2], dp[i - 3] + count[num] * num)\n\n # otherwise, we can use spell nums[i - 3] with spell nums[i - 1]\n else:\n dp[i] = max(dp[i - 1], dp[i - 2] + count[num] * num)\n return dp[-1]\n \n``` | 5 | 0 | ['Python3'] | 2 |
maximum-total-damage-with-spell-casting | Simple DFS solution | simple-dfs-solution-by-0x4c0de-h4j1 | Intuition\n Describe your first thoughts on how to solve this problem. \nWe have two choices with each distinct power.\n\n### Approach\n Describe your approach | 0x4c0de | NORMAL | 2024-06-16T04:00:42.226593+00:00 | 2024-06-16T04:24:16.257707+00:00 | 875 | false | ### Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe have two choices with each **distinct** power.\n\n### Approach\n<!-- Describe your approach to solving the problem. -->\nUse map to count the power, and DFS with cache to search the best result.\n\n`TreeMap` can sort the power and it\'s `ceil` to get next usable power.\n\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 {\n public long maximumTotalDamage(int[] power) {\n TreeMap<Integer, Integer> count = new TreeMap<>();\n for (int p : power) {\n count.merge(p, 1, Integer::sum);\n }\n\n Map<Integer, Long> cache = new HashMap<>();\n\n return dfs(count.firstKey(), count, cache);\n }\n\n private long dfs(Integer power, TreeMap<Integer, Integer> count, Map<Integer, Long> cache) {\n if (null == power) {\n return 0;\n }\n\n if (cache.containsKey(power)) {\n return cache.get(power);\n }\n\n // pick the current power\n long pick = (long) power * count.get(power) +\n // at least power + 3\n dfs(count.ceilingKey(power + 3), count, cache);\n\n // unpick the current power\n long unpick =\n dfs(\n // at least power + 1\n count.ceilingKey(power + 1), count, cache);\n\n long best = Math.max(pick, unpick);\n cache.put(power, best);\n\n return best;\n }\n}\n``` | 5 | 0 | ['Depth-First Search', 'Java'] | 2 |
maximum-total-damage-with-spell-casting | simple recursion +memoization | simple-recursion-memoization-by-demon_co-3bez | First of all sort the power array bcz it doesn\'t matter how we use powers while following the given rule ,\nthe effect of sorting will be if we have selected t | demon_code | NORMAL | 2024-06-26T11:39:09.621278+00:00 | 2024-06-26T11:39:09.621312+00:00 | 59 | false | First of all sort the power array bcz it doesn\'t matter how we use powers while following the given rule ,\nthe effect of sorting will be if we have selected the current element then we can skip next elements which are in +1 and +2 range and call the function after skipping. and we don\'t have to worry about smaller elements.\n\nit all depend upon current choises ; if we select the ```current element i``` then we have to skip +1, +2 elements as we have sorted the array we can use while loop to ignore these elements and call from next suitable index\n\nif we don\'t select the current one then we can always call from ```i+1``` bcz ```i``` was an eligible element and we didn\'t pick it means i+1 will be always eligible as power[i+1]>=power[i] after sorting.\n\ntake max of both branches and memoize the solution ```:)```\none more thing store frequency for repeted elements and use unique array for solution (will help to avoid tle in extreme repitations)\n\n\n```\nclass Solution {\npublic:\n int n;\n vector<int>a; // unique array\n map<int,int> m; // frequency map\n long long dp[100002]; // memoization\n long long solve(int i)\n {\n if(i==n) return 0;\n if(dp[i]!=-1) return dp[i];\n \n \n // don\'t take it\n long long ans= solve(i+1);\n long long t=0;\n // take it \n \n int k=i;\n t+=1ll*a[i]* m[a[i]];\n while(k<n && a[k]-a[i]<=2) k++;\n \n t+=solve(k);\n \n return dp[i]=max(ans, t);\n \n }\n long long maximumTotalDamage(vector<int>& p) {\n memset(dp,-1,sizeof(dp));\n for(auto i: p) m[i]++; // calculating frequency\n for(auto i: m) a.push_back(i.first); // store only unique elements\n n=a.size(); // size of unique array\n \n return solve(0);\n \n }\n};\n\n\n\n``` | 4 | 0 | ['Recursion', 'Memoization', 'C'] | 0 |
maximum-total-damage-with-spell-casting | 🔥DP || ⚡Memoization || ✅Clean & Easy to understand || Beginner Friendly Solution💯 || | dp-memoization-clean-easy-to-understand-2ynw0 | Intuition\n Describe your first thoughts on how to solve this problem. \nThe key is to decide whether to include or exclude a spell with a particular damage and | virender_kumar | NORMAL | 2024-06-16T06:24:41.506148+00:00 | 2024-06-16T06:24:41.506194+00:00 | 248 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe key is to decide whether to include or exclude a spell with a particular damage and then use that decision to maximize the total damage. Its a simple pick or not pick problem in dynamic programming.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Preprocessing:\n\nThe power array is converted into a frequency map mp where mp[d] counts the occurrences of each damage value d.\nA list unique_power is created containing the unique damage values sorted in ascending order.\n\n2. Dynamic Programming Setup:\n\ndp is a memoization table where dp[index] will store the maximum possible damage starting from the spell at unique_power[index].\n\n3. Recursive Function:\n\nThe function solve_dp is defined to recursively compute the maximum damage starting from a given index.\nBase Case: If index is out of bounds, return 0.\nMemoization Check: If the result for the current index is already computed (i.e., dp[index] is not -1), return the memoized result.\n\n4. Decision Making:\n\nPick: Choose the spell at unique_power[index]. To do this, add the damage contribution mp[unique_power[index]] * unique_power[index] and move to the next index that is at least 3 positions ahead (due to the constraint).\nNot Pick: Skip the current spell and move to the next index.\nStore the maximum value of picking or not picking the current spell in dp[index].\n\n5. Final Computation:\n\nStart the recursive computation from the first index and return the result.\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(m), m <= n\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n long long solve_dp(int index, vector<int>& unique_power, vector<long long>& dp, map<int, int>& mp) \n {\n int n = unique_power.size();\n if (index >= n) \n {\n return 0;\n }\n if (dp[index] != -1) return dp[index];\n\n long long pick = 0; \n int next_index = index + 1;\n while (next_index < n && unique_power[next_index] - unique_power[index] <= 2) \n {\n next_index++;\n }\n pick = (long long)mp[unique_power[index]] * unique_power[index] + solve_dp(next_index, unique_power, dp, mp);\n long long not_pick = solve_dp(index + 1, unique_power, dp, mp);\n \n return dp[index] = max(pick, not_pick);\n }\n\n long long maximumTotalDamage(vector<int>& power) \n {\n int n = power.size();\n\n map<int, int> mp;\n vector<long long> dp(n, -1);\n vector<int> unique_power;\n for(int i = 0; i < n; i++)\n {\n mp[power[i]]++;\n }\n for(auto itr = mp.begin(); itr != mp.end(); itr++)\n {\n unique_power.push_back(itr->first);\n }\n return solve_dp(0, unique_power, dp, mp);\n }\n};\n\n``` | 4 | 0 | ['Dynamic Programming', 'Memoization', 'C++'] | 2 |
maximum-total-damage-with-spell-casting | ✅✅ Faster than 100% Solution | Memoization 🤩🤩😱😱 | faster-than-100-solution-memoization-by-gj9so | Intuition\n Describe your first thoughts on how to solve this problem. \nTo maximize the total damage by selecting elements from the array p, ensuring that sele | Rishu_Raj5938 | NORMAL | 2024-06-16T05:44:53.845458+00:00 | 2024-06-17T07:18:29.010209+00:00 | 244 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo maximize the total damage by selecting elements from the array p, ensuring that selecting one element restricts selecting nearby values (e.g., values differing by 1 or 2).\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFrequency Map (mp):\nCount occurrences of each element in p.\n\nUnique Elements Vector (v):\nExtract unique elements from the frequency map and sort them.\n\nMemoization Array (dp):\nInitialize an array to store results of subproblems, avoiding redundant calculations.\n\nRecursive Function (solve):\n\nBase Case: If index idx is out of bounds, return 0.\n\nMemoization Check: If result for idx is already computed, return it.\n\nNot Take (not_take): Calculate damage if the current element is skipped.\n\nTake (take): Calculate damage if the current element is taken, adding its damage and recursively solving for the appropriate next index based on adjacency rules.\n\nResult Storage:\nStore the maximum of take and not_take in dp[idx] and return it.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(m+nlogn)\n\nwhere \uD835\uDC5A is the number of elements in the input vector p, and \n\uD835\uDC5B is the number of unique elements in p.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(m)\n\nwhere m is the number of elements in the input vector p, and \n\uD835\uDC5B is the number of unique elements in p. Given that \n\uD835\uDC5B \u2264 \uD835\uDC5A\n\n\nPlease Upvote if found helpful.\n\n\n\n\n# Code\n```\nclass Solution {\npublic:\n #define ll long long\n unordered_map<long long, int> mp;\n int n;\n long long dp[100002];\n \n long long solve(vector<long long>&v, int idx) {\n \n if(idx >= n) return 0;\n \n if(dp[idx] != -1) return dp[idx];\n \n long long not_take = solve(v, idx+1);\n \n int next = idx+3;\n\n if(idx < n-1) {\n\n if(v[idx+1]-v[idx] > 2) next = idx+1;\n else if(idx < n-2 && v[idx+1]-v[idx] == 2) next = idx+2;\n else if(idx < n-2 && v[idx+1]-v[idx] == 1 && v[idx+2]-v[idx+1] > 1) next = idx+2;\n\n }\n \n ll take = v[idx]*mp[v[idx]] + solve(v, next);\n \n return dp[idx] = max(take, not_take);\n }\n \n long long maximumTotalDamage(vector<int>& p) {\n \n for(int i=0; i<p.size(); i++) {\n mp[p[i]]++;\n }\n \n memset(dp, -1, sizeof(dp));\n \n vector<long long> v;\n \n for(auto it : mp) v.push_back(it.first);\n \n sort(v.begin(), v.end());\n \n n = v.size();\n \n return solve(v, 0); \n }\n};\n\n\n``` | 4 | 0 | ['C++'] | 1 |
maximum-total-damage-with-spell-casting | Simple 13-line DP + Sorting, explained O(n log n) | simple-13-line-dp-sorting-explained-on-l-39q2 | It is obvious that if we take a spell, we should take all of the spells with the same value, as doing so doesn\'t impose any more restrictions. Then, the next l | t747 | NORMAL | 2024-06-16T04:00:28.967322+00:00 | 2024-06-16T04:00:28.967354+00:00 | 915 | false | It is obvious that if we take a spell, we should take all of the spells with the same value, as doing so doesn\'t impose any more restrictions. Then, the next lowest spell that we can consider taking is a spell with at least 3 more damage. So create two arrays, a sum array, and a next index array, to efficiently skip all duplicates and go to the next spell we can take. Then simply do take-not-take DP on the spells.\n\n\n```\npublic:\n long long dp[100001] = {};\n long long dfs(int pos, vector<int>& power, vector<long long>& sum, vector<int>& next) {\n if(pos>=power.size()) return 0;\n if(dp[pos] != -1) return dp[pos];\n long long ans = max (dfs(pos+1, power, sum, next), dfs(next[pos], power, sum, next)+sum[pos]);\n return dp[pos] = ans;\n }\n long long maximumTotalDamage(vector<int>& power) {\n sort(power.begin(),power.end());\n for (int i = 0; i < power.size(); i++) dp[i] = -1;\n \n vector<long long> sum;\n for (auto i : power) sum.push_back(i);\n for (int i = 1; i < power.size(); i++) if (power[i] == power[i-1]) sum[i] += sum[i-1];\n for (int i = sum.size()-2; i >= 0; i--) if (power[i+1] == power[i]) sum[i] = sum[i+1];\n \n vector<int> next = power;\n for (int i = 0; i < power.size(); i++) next[i] = lower_bound(power.begin(), power.end(), power[i]+3) - power.begin();\n \n return dfs(0, power, sum, next);\n } | 4 | 0 | [] | 1 |
maximum-total-damage-with-spell-casting | Memoization Very simple approach | memoization-very-simple-approach-by-kain-mojw | Intuition\n1. Sorting and Frequency Counting:\n\n- First, we sort the array of spell damage values in increasing order. This helps us ensure that when traversin | KaintCode | NORMAL | 2024-06-16T04:55:55.683828+00:00 | 2024-06-16T05:17:54.221865+00:00 | 342 | false | # Intuition\n1. Sorting and Frequency Counting:\n\n- First, we sort the array of spell damage values in increasing order. This helps us ensure that when traversing the array, we move from lower damage values to higher ones.\n- Then, we count the frequency of each unique spell damage value and store it in a map for easy access.\n2. Traversing with Recursion:\n\n- With the sorted and frequency-counted array, we begin traversing using recursion.\n- At each step, we have two choices: either we consider casting the current spell or we skip it.\n3. Considering the Current Element:\n\n- If we decide to consider casting the current spell, we have several cases to handle to ensure we comply with the restriction:\nFirst, we take the current spell, represented by the current element in the sorted array.\n- We then check if the next spell\'s damage value is greater than the current spell\'s damage value plus 2. If it is, we consider it a valid next spell to cast.\n- We also check if the spell two positions ahead is greater than the current spell\'s damage value plus 2. If it is, we consider it a valid spell to cast after skipping one spell.\n- Finally, we recursively explore the possibility of skipping the next two spells and directly jumping to the spell after that. Since the array is sorted, the spell after the next two positions is guaranteed to have a damage value greater than the current spell\'s damage value plus 2.\n\nBy systematically considering these cases and optimizing the recursion process with the sorted array and frequency count, we can efficiently compute the maximum total damage the magician can cast while adhering to the given restrictions. This approach ensures that we explore only valid spell combinations, avoiding redundant calculations and improving the overall performance of the algorithm.\n \n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n unordered_map<int,long long>freq;\n long long getAns(vector<int>&pows,int n,int ind,vector<long long>&dp){\n if(ind>=n){\n return 0;\n }\n if(dp[ind]!=-1)\n return dp[ind];\n \n long long take=0,notTake=0,val=0,val1=0,val2=0,val3=0,val4=0;\n take=(long long)(freq[pows[ind]]*pows[ind]);\n if(ind+1<n && pows[ind+1]-pows[ind]>2){\n val1=getAns(pows,n,ind+1,dp);\n }\n if(ind+2<n && pows[ind+2]-pows[ind]>2){\n val2=getAns(pows,n,ind+2,dp);\n }\n val3=getAns(pows,n,ind+3,dp);\n val4=getAns(pows,n,ind+1,dp);\n \n\n val=take+max(val1,max(val2,val3));\n return dp[ind]=max(val,val4);\n \n }\n \n long long maximumTotalDamage(vector<int>& power) {\n \n \n for(auto it:power){\n freq[it]++;\n }\n unordered_set<int>st(power.begin(),power.end());\n vector<int>temp;\n for(auto it:st)\n temp.push_back(it);\n sort(temp.begin(),temp.end());\n int n=temp.size();\n vector<long long>dp(n+1,-1);\n return getAns(temp,n,0,dp);\n }\n};\n``` | 3 | 0 | ['Dynamic Programming', 'Memoization', 'Sorting', 'Ordered Set', 'C++'] | 0 |
maximum-total-damage-with-spell-casting | [Python] DP Knapsack (Simple, full explanations!) | python-dp-knapsack-simple-full-explanati-vonf | Approach\nWe first put all values of power into a frequency array, so that we can compute the total damage we deal by only using this specific power in O(1) tim | zzzqwq | NORMAL | 2024-06-16T04:36:42.272913+00:00 | 2024-06-16T04:36:42.272930+00:00 | 222 | false | # Approach\nWe first put all values of `power` into a frequency array, so that we can compute the total damage we deal by only using this specific power in $$O(1)$$ time by using $$freq[n]*n$$ (n is any number here). \n\nThen we realize that this problem is very similar to the 0/1 knapsack problem, where we can only add the damage together if the power is at least more than $$2$$ less than the current power of the spell.\n\nDP state: $$dp[i]$$ = maximum damage dealt with the first $$i$$ unique spells (sorted order)\n\nWe can model this by using the following dp transition:\n```\nif p[i]-p[i-1]>2:\n dp[i] = max(dp[i], dp[i-1]+dmg)\nif p[i]-p[i-2]>2:\n dp[i] = max(dp[i], dp[i-2]+dmg)\ndp[i] = max(dp[i], dp[i-3]+dmg, dp[i-1])\n```\nIf the last spell cast already was $$2$$ less than the current spell, we can simply add the previous dp answer to `dmg`, which would give us the best answer.\n\nIf not, we check the same for the second last spell cast ($$i-2$$), repeating the same precedures.\n\nThen, just for a last check, we take the max of $$dp[i-3]$$, which is **guarenteed** to be at least $$2$$ smaller than the current spell value, since every cell of dp represents maximum damage dealt with the largest spell being unique. We also take the max of the current dp cell, $$dp[i]$$, and the previous cell, $$dp[i-1]$$, to ensure that $$dp[i]$$ always matches our definition. \n\n# Code\n```\nclass Solution:\n def maximumTotalDamage(self, power: List[int]) -> int:\n freq = defaultdict(int)\n for i in power:\n freq[i] += 1\n p = [0] + sorted(freq.keys())\n N = len(p)\n if N-1 == 1:\n return freq[p[1]]*p[1]\n dp = [0] * N\n dp[1] = freq[p[1]]*p[1]\n dp[2] = max(freq[p[2]]*p[2] + (dp[1] if p[2]-p[1]>2 else 0), dp[1])\n for i in range(3, N):\n dmg = p[i] * freq[p[i]]\n if p[i]-p[i-1]>2:\n dp[i] = max(dp[i], dp[i-1]+dmg)\n if p[i]-p[i-2]>2:\n dp[i] = max(dp[i], dp[i-2]+dmg)\n dp[i] = max(dp[i], dp[i-3]+dmg, dp[i-1])\n return dp[N-1]\n \n``` | 3 | 0 | ['Dynamic Programming', 'Python3'] | 0 |
maximum-total-damage-with-spell-casting | Dynamic Programming - Easy Solution Detailed Explanation | dynamic-programming-easy-solution-detail-9gyp | Intuition\n\nThe goal is to maximize the total damage by selecting powers in a way that no two selected powers differ by 2 or less. This problem can be solved u | chirag45610 | NORMAL | 2024-06-16T04:01:33.488058+00:00 | 2024-06-16T04:01:33.488094+00:00 | 345 | false | ### Intuition\n\nThe goal is to maximize the total damage by selecting powers in a way that no two selected powers differ by 2 or less. This problem can be solved using dynamic programming by leveraging the sorted unique values of power and computing the maximum damage incrementally.\n\n### Approach\n\n1. **Handle Edge Case**: If the `power` array is empty, return 0 immediately.\n2. **Count Occurrences**: Use a hash map (`mp`) to count the frequency of each power value.\n3. **Extract and Sort Unique Values**:\n - Extract unique power values from the hash map and store them in a vector (`ud`).\n - Sort the `ud` vector.\n4. **Initialize DP Array**: Create a `dp` array to store the maximum damage up to each unique power value.\n5. **DP Initialization**:\n - Set the first value in `dp` to the product of the first unique power and its frequency.\n6. **Iterate and Compute DP**:\n - For each subsequent unique power, calculate the potential maximum damage by including the current power value.\n - Check previous values in `dp` to ensure no two selected powers differ by 2 or less.\n - Update the `dp` array with the maximum of the current value or the previously computed maximum.\n7. **Return Result**: The last value in the `dp` array contains the maximum total damage.\n\n### Complexity Analysis\n\n#### Time Complexity\n1. **Counting Occurrences**: Iterating through the `power` array and counting frequencies takes \\(O(n)\\), where \\(n\\) is the number of elements in `power`.\n2. **Sorting Unique Values**: Sorting the unique values takes \\(O(k \\log k)\\), where \\(k\\) is the number of unique power values.\n3. **DP Calculation**: Iterating through the `ud` array and calculating the `dp` values takes \\(O(k^2)\\) in the worst case due to the nested while loop.\n\nThus, the overall time complexity is \\(O(n + k \\log k + k^2)\\).\n\n#### Space Complexity\n- **Hash Map**: The hash map stores counts of unique power values, taking \\(O(k)\\) space.\n- **DP Array**: The `dp` array stores the maximum damage up to each unique power, taking \\(O(k)\\) space.\n\nThus, the overall space complexity is \\(O(k)\\).\n\n### Detailed Walkthrough\n\nConsider the array `power = [1, 2, 3, 4, 5, 6, 6]`.\n\n1. **Initialization**:\n - `mp = {1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 2}`\n - `ud = [1, 2, 3, 4, 5, 6]`\n\n2. **Sort Unique Values**:\n - `ud = [1, 2, 3, 4, 5, 6]` (already sorted)\n\n3. **Initialize DP Array**:\n - `dp = [0, 0, 0, 0, 0, 0]`\n - `dp[0] = 1 * 1 = 1`\n\n4. **DP Calculation**:\n - For `i = 1` (power 2):\n - `current = 2 * 1 = 2`\n - No previous valid values, so `dp[1] = max(dp[0], 2) = 2`\n - For `i = 2` (power 3):\n - `current = 3 * 1 = 3`\n - No previous valid values, so `dp[2] = max(dp[1], 3) = 3`\n - For `i = 3` (power 4):\n - `current = 4 * 1 = 4`\n - Valid previous value at `j = 0` (power 1), `current = 4 + 1 = 5`\n - `dp[3] = max(dp[2], 5) = 5`\n - For `i = 4` (power 5):\n - `current = 5 * 1 = 5`\n - Valid previous value at `j = 1` (power 2), `current = 5 + 2 = 7`\n - `dp[4] = max(dp[3], 7) = 7`\n - For `i = 5` (power 6):\n - `current = 6 * 2 = 12`\n - Valid previous value at `j = 2` (power 3), `current = 12 + 3 = 15`\n - `dp[5] = max(dp[4], 15) = 15`\n\nFinally, the maximum total damage (`dp[5]`) is 15.\n\n### Code\n\n```cpp\nclass Solution {\npublic:\n long long maximumTotalDamage(vector<int>& power) {\n if (power.empty())\n return 0;\n\n unordered_map<int, int> mp;\n for (int p : power) \n mp[p]++;\n\n vector<int> ud;\n for (auto& pair : mp) \n ud.push_back(pair.first);\n \n sort(ud.begin(), ud.end());\n\n int n = ud.size();\n vector<long long> dp(n, 0);\n\n dp[0] = static_cast<long long>(ud[0]) * static_cast<long long>(mp[ud[0]]);\n\n for (int i = 1; i < n; ++i) {\n int cd = ud[i];\n long long current = static_cast<long long>(cd) * mp[cd];\n\n int j = i - 1;\n while (j >= 0 && (cd - ud[j] <= 2)) \n j--;\n\n if (j >= 0) \n current += dp[j];\n\n dp[i] = max(dp[i - 1], current);\n }\n return dp[n - 1];\n }\n};\n```\n\nThis approach ensures that the maximum total damage is computed efficiently while respecting the constraint that no two selected powers differ by 2 or less. | 3 | 0 | ['C++'] | 0 |
maximum-total-damage-with-spell-casting | Beats 77% Solution Binary Search + Dp | beats-77-solution-binary-search-dp-by-sh-il8y | Code | shlok1913 | NORMAL | 2025-01-31T17:08:49.183700+00:00 | 2025-01-31T17:08:49.183700+00:00 | 65 | false |
# Code
```cpp []
class Solution {
public:
vector<long long>dp;
long long solve(int i , vector<int>&p) {
if (i >= p.size()) return 0;
if (dp[i] != -1) return dp[i];
int j = lower_bound(p.begin() , p.end() , p[i]+3) - p.begin();
int k = lower_bound(p.begin() , p.end() , p[i]+1) - p.begin();
long long take = (long long)p[i] * (k - i) + solve(j,p);
long long notTake = 0 + solve(i+1,p);
return dp[i]=max(take , notTake);
}
long long maximumTotalDamage(vector<int>& p) {
sort(p.begin(),p.end());
dp.resize(p.size()+1 ,-1);
return solve(0 , p);
}
};
``` | 2 | 0 | ['Binary Search', 'Dynamic Programming', 'Sorting', 'C++'] | 0 |
maximum-total-damage-with-spell-casting | recursion with dp | recursion-with-dp-by-happygarg-oom8 | Intuition\n Describe your first thoughts on how to solve this problem. \ndid a problem number 740 on leetcode.\n\n# Approach\n Describe your approach to solving | happygarg | NORMAL | 2024-11-25T17:10:00.399252+00:00 | 2024-11-25T17:10:00.399296+00:00 | 24 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\ndid a problem number 740 on leetcode.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nsimply find all the unique numbers and store their frquency.\nthen sort the array of unique numbers and now it is very clear that only next two element can be num+1,num+2 so increasing the index accordingly that\'s it.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n+mlogm)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(m)\n\n# Code\n```cpp []\nclass Solution {\npublic:\n long long solve(int idx, vector<int>& v, unordered_map<int, int>& mp, vector<long long>& dp) {\n if (idx >= v.size()) return 0; // Base case: no more elements to process\n if (dp[idx] != -1) return dp[idx]; // Return memoized result\n\n // Option 1: Do not take the current value\n long long notake = solve(idx + 1, v, mp, dp);\n\n // Option 2: Take the current value\n long long take = (long long)v[idx] * mp[v[idx]]; // Current damage\n int nextIdx = idx + 1;\n\n // Skip indices that conflict with the current value\n while (nextIdx < v.size() && v[nextIdx] <= v[idx] + 2) {\n nextIdx++;\n }\n take += solve(nextIdx, v, mp, dp);\n\n // Memoize and return the maximum of both options\n return dp[idx] = max(notake, take);\n }\n\n long long maximumTotalDamage(vector<int>& power) {\n unordered_map<int, int> mp;\n\n // Step 1: Aggregate the frequency of each damage value\n for (int num : power) {\n mp[num]++;\n }\n\n // Step 2: Extract unique damage values and sort them\n vector<int> v;\n for (auto it : mp) {\n v.push_back(it.first);\n }\n sort(v.begin(), v.end());\n\n // Step 3: Initialize dp array for memoization\n vector<long long> dp(v.size(), -1);\n\n // Step 4: Solve using the recursive function\n return solve(0, v, mp, dp);\n }\n};\n\n``` | 2 | 0 | ['C++'] | 0 |
maximum-total-damage-with-spell-casting | dp | dp-by-anil-budamakuntla-pkvo | 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 | ANIL-BUDAMAKUNTLA | NORMAL | 2024-06-21T01:14:58.803095+00:00 | 2024-06-21T01:14:58.803112+00:00 | 21 | 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: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 long long maximumTotalDamage(vector<int>& p) {\n \n long long i,j=0,k=0,ans=0,n=p.size(),m;\n sort(p.begin(),p.end());\n vector<long long>v;\n map<long long,long long>mp;\n for(i=0;i<n;i++)\n {\n m=p[i];\n if(mp[m]==0)\n {\n v.push_back(m);\n }\n mp[m]++;\n }\n n=mp.size();\n vector<long long>dp(n+1,0);\n \n for(i=0;i<n;i++)\n {\n j=i-1;\n k=0;\n while(j>=0)\n {\n if((v[j]!=v[i]-1)&&(v[j]!=v[i]-2))\n {\n dp[i]=dp[j];\n break;\n }\n j--;\n }\n dp[i]+=mp[v[i]]*v[i];\n ans=max(dp[i],ans);\n dp[i]=ans;\n \n }\n return dp[n-1];\n \n }\n};\n```\n\n | 2 | 0 | ['Dynamic Programming', 'C++'] | 2 |
maximum-total-damage-with-spell-casting | Beats 100% || DP(Tabulation)+Binary Search || Clean Code | beats-100-dptabulationbinary-search-clea-3rvc | Intuition\nUse dynamic programming to keep track of the maximum damage at each step while considering the constraint that an element can only be added if its va | praneki_ | NORMAL | 2024-06-17T07:40:03.688895+00:00 | 2024-06-17T07:40:03.688925+00:00 | 64 | false | # Intuition\nUse dynamic programming to keep track of the maximum damage at each step while considering the constraint that an element can only be added if its value is at least 2 greater than some previously considered element.\n\nIn order to find which elements can contribute to the current element\'s damage without violating the constraint\n Use binary search (via lower_bound) to find the largest index of an element that is less than power[i] - 2.\n\n# Approach\n1. **Sort the Array**: Sort the power array to facilitate binary search.\n\n2. **Find Valid Indices**: \n - Use binary search (`lower_bound`) to find the largest index with a value less than `power[i] - 2` for each element in the sorted array.\n - Store these indices in a `last` vector,corresponding each element.\n\n3. **Dynamic Programming**:\n - Initialize a `dp` vector where `dp[i]` represents the maximum damage achievable up to index `i`.\n - Use a cumulative sum `cotd` to handle consecutive elements with the same value.\n4. The last value in the `dp` array (`dp[n-1]`) is the maximum total damage.\n\n\n# Complexity\n- Time complexity:\n$$O(nLog(n))$$ \n\n- Space complexity:\n$$O(n)$$ \n\n# Code\n```\nclass Solution {\npublic:\n // Function to find the largest index of an element less than the given value using binary search\n int findIndexLessThan(const std::vector<int>& nums, int value) {\n // Use lower_bound to find the first element not less than the value\n auto it = std::lower_bound(nums.begin(), nums.end(), value);\n // If it points to the beginning, no element is less than the value\n if (it == nums.begin()) return -1;\n // Move the iterator one step back to get the largest element less than the value\n return std::distance(nums.begin(), --it);\n }\n\n \n long long maximumTotalDamage(vector<int>& power) {\n sort(power.begin(), power.end());//sort for binary search\n int n = power.size();\n // Vector to store the largest index with value less than power[i] - 2\n vector<int> last(n, 0);\n for (int i = 0; i < n; ++i) {\n // Populate the last array with indices of valid elements\n last[i] = findIndexLessThan(power, power[i] - 2);\n }\n\n // Vector to store the maximum damage up to each index\n vector<long long> dp(n, 0);\n // Variable to store cumulative damage of consecutive elements with the same value\n long long cotd = 0;\n\n \n for (int i = 0; i < n; ++i) {\n // Get the maximum damage up to the previous index\n long long lastNum = (i > 0) ? dp[i - 1] : 0;\n // Get the maximum damage from the valid previous element\n long long pick = (last[i] != -1) ? dp[last[i]] : 0;\n // Calculate the maximum damage including the current element\n dp[i] = max(lastNum, power[i] + pick + cotd);\n // Update the cumulative damage for consecutive elements with the same value\n if (i < n - 1 && power[i] == power[i + 1]) cotd += power[i];\n else cotd = 0;\n }\n\n // Return the maximum total damage\n return dp[n - 1];\n }\n};\n\n``` | 2 | 0 | ['Binary Search', 'Dynamic Programming', 'C++'] | 0 |
maximum-total-damage-with-spell-casting | 🔥Beats 100% || Intution || Memoization -> Tabulation -> Space Opti || CPP || JAVA || PYTHON || TS | beats-100-intution-memoization-tabulatio-hd6k | Intuition\n Describe your first thoughts on how to solve this problem. \nThis problem is similar to the "House Robber" problem with additional constraints on wh | IchigoGoes | NORMAL | 2024-06-16T14:23:06.079676+00:00 | 2024-06-17T18:14:23.894967+00:00 | 285 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis problem is similar to the "House Robber" problem with additional constraints on which spells can be cast. If we cast a spell with damage power[i], we can\'t cast spells with adjacent damages in the range of power[i] - 2 to power[i] + 2.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Frequency Count**: First, count the frequency of each spell damage using a hash map. Why ? If you wanna use a spell you might as well just use all occurences of it. That\'s one thing you should really observe.\n\n2. **Unique and Sorted Damages**: Store the unique spell damages in a sorted list.\n3. **Dynamic Programming**: Use dynamic programming to keep track of the maximum possible damage up to each point, considering the constraints of not casting spells with adjacent damages.\n4. **BONUS:** : Do not use AI tools for such questions. Chatgpt might give you a concise and space optimised solution, but you\'ll never learn anything from that code if you couldn\'t write the recursive relations on your own. Write Recursion and practice. Here\'s a similar problem for your practice :\n``` https://leetcode.com/problems/delete-and-earn/```\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) For tab \n O(1) for Space optimisation\n# Code : \n## C++\n\n```cpp [Memoization]\n#define ll long long\n\nclass Solution {\npublic:\n unordered_map<int,int> m ;\n ll dp[100001];\n \n ll f(int ind,vector<int>&power){\n int n = power.size();\n if (ind>=power.size())return 0 ;\n\n if (dp[ind]!=-1)return dp[ind];\n\n ll np = f(ind+1,power);\n ll p = 1LL*power[ind]*m[power[ind]];\n\n if (ind+1 < n and power[ind+1] != power[ind]+1 and power[ind+1]!=power[ind]+2){\n p +=f(ind+1,power);\n } \n else if (ind+2 < n and power[ind+2] != power[ind]+2){\n p+=f(ind+2,power);\n }\n else if (ind+3<n){\n p+=f(ind+3,power);\n }\n return dp[ind] = max(p,np);\n }\n\n long long maximumTotalDamage(vector<int>& power) {\n memset(dp,-1,sizeof(dp));\n for(int &i : power)m[i]++;\n //1 6 7 \n power.clear();\n for(auto &i : m)power.push_back(i.first);\n sort(power.begin(),power.end());\n return f(0,power);\n }\n};\n```\n```cpp [Tabulation]\n#define ll long long\n\nclass Solution {\npublic:\n long long maximumTotalDamage(vector<int>& power) {\n unordered_map<int, int> freq;\n for (int dmg : power) {\n freq[dmg]++;\n }\n\n vector<int> uniquePower;\n for (auto& entry : freq) {\n uniquePower.push_back(entry.first);\n }\n sort(uniquePower.begin(), uniquePower.end());\n\n int n = uniquePower.size();\n vector<ll> dp(n + 1, 0);\n\n for (int i = n - 1; i >= 0; --i) {\n ll pick = uniquePower[i] * freq[uniquePower[i]];\n int j = i + 1;\n while (j < n && (uniquePower[j] == uniquePower[i] + 1 || uniquePower[j] == uniquePower[i] + 2)) {\n ++j;\n }\n if (j < n) {\n pick += dp[j];\n }\n\n ll notPick = dp[i + 1];\n\n dp[i] = max(pick, notPick);\n }\n\n return dp[0];\n }\n};\n```\n```cpp [Space Optimisation]\n#define ll long long\n\nclass Solution {\npublic:\n long long maximumTotalDamage(vector<int>& power) {\n unordered_map<int, int> freq;\n for (int dmg : power) {\n freq[dmg]++;\n }\n\n vector<int> uniquePower;\n for (auto& entry : freq) {\n uniquePower.push_back(entry.first);\n }\n sort(uniquePower.begin(), uniquePower.end());\n ll prev2 = 0; // dp[i-2]\n ll prev1 = 0; // dp[i-1]\n for (int i = 0; i < uniquePower.size(); ++i) {\n ll current = (ll)uniquePower[i] * freq[uniquePower[i]];\n\n if (i > 0 && uniquePower[i] == uniquePower[i - 1] + 1) {\n current += prev2;\n } else {\n current += prev1;\n }\n\n // Update prev2 and prev1 for next iteration\n prev2 = prev1;\n prev1 = current;\n }\n return max(prev2, prev1);\n }\n};\n```\n\n## Java: \n```java [Memo]\nimport java.util.*;\n\nclass Solution {\n Map<Integer, Integer> freq;\n long[] dp;\n\n public long maximumTotalDamage(int[] power) {\n freq = new HashMap<>();\n for (int dmg : power) {\n freq.put(dmg, freq.getOrDefault(dmg, 0) + 1);\n }\n\n List<Integer> uniquePower = new ArrayList<>(freq.keySet());\n Collections.sort(uniquePower);\n\n dp = new long[uniquePower.size()];\n Arrays.fill(dp, -1);\n\n return f(0, uniquePower);\n }\n\n private long f(int ind, List<Integer> power) {\n int n = power.size();\n if (ind >= n) return 0;\n\n if (dp[ind] != -1) return dp[ind];\n\n long np = f(ind + 1, power);\n long p = 1L * power.get(ind) * freq.get(power.get(ind));\n\n if (ind + 1 < n && power.get(ind + 1) != power.get(ind) + 1 && power.get(ind + 1) != power.get(ind) + 2) {\n p += f(ind + 1, power);\n } else if (ind + 2 < n && power.get(ind + 2) != power.get(ind) + 2) {\n p += f(ind + 2, power);\n } else if (ind + 3 < n) {\n p += f(ind + 3, power);\n }\n \n return dp[ind] = Math.max(p, np);\n }\n}\n\n```\n```java [Tabulation]\nimport java.util.*;\n\nclass Solution {\n public long maximumTotalDamage(int[] power) {\n Map<Integer, Integer> freq = new HashMap<>();\n for (int dmg : power) {\n freq.put(dmg, freq.getOrDefault(dmg, 0) + 1);\n }\n\n List<Integer> uniquePower = new ArrayList<>(freq.keySet());\n Collections.sort(uniquePower);\n\n int n = uniquePower.size();\n long[] dp = new long[n + 1];\n\n for (int i = n - 1; i >= 0; --i) {\n long pick = (long) uniquePower.get(i) * freq.get(uniquePower.get(i));\n int j = i + 1;\n while (j < n && (uniquePower.get(j) == uniquePower.get(i) + 1 || uniquePower.get(j) == uniquePower.get(i) + 2)) {\n ++j;\n }\n if (j < n) {\n pick += dp[j];\n }\n\n long notPick = dp[i + 1];\n\n dp[i] = Math.max(pick, notPick);\n }\n\n return dp[0];\n }\n}\n\n```\n```java [Space Opti]\nimport java.util.*;\n\nclass Solution {\n public long maximumTotalDamage(int[] power) {\n Map<Integer, Integer> freq = new HashMap<>();\n for (int dmg : power) {\n freq.put(dmg, freq.getOrDefault(dmg, 0) + 1);\n }\n\n List<Integer> uniquePower = new ArrayList<>(freq.keySet());\n Collections.sort(uniquePower);\n\n long prev2 = 0; // dp[i-2]\n long prev1 = 0; // dp[i-1]\n for (int i = 0; i < uniquePower.size(); ++i) {\n long current = (long) uniquePower.get(i) * freq.get(uniquePower.get(i));\n\n if (i > 0 && uniquePower.get(i) == uniquePower.get(i - 1) + 1) {\n current += prev2;\n } else {\n current += prev1;\n }\n\n // Update prev2 and prev1 for next iteration\n prev2 = prev1;\n prev1 = current;\n }\n\n return Math.max(prev2, prev1);\n }\n}\n```\n\n## Python: \n\n```python [Memo]\nclass Solution:\n def maximumTotalDamage(self, power: List[int]) -> int:\n freq = {}\n for dmg in power:\n if dmg in freq:\n freq[dmg] += 1\n else:\n freq[dmg] = 1\n \n unique_power = sorted(freq.keys())\n \n @cache\n def f(ind):\n if ind >= len(unique_power):\n return 0\n \n np = f(ind + 1)\n p = unique_power[ind] * freq[unique_power[ind]]\n \n if ind + 1 < len(unique_power) and unique_power[ind + 1] != unique_power[ind] + 1 and unique_power[ind + 1] != unique_power[ind] + 2:\n p += f(ind + 1)\n elif ind + 2 < len(unique_power) and unique_power[ind + 2] != unique_power[ind] + 2:\n p += f(ind + 2)\n elif ind + 3 < len(unique_power):\n p += f(ind + 3)\n \n return max(p, np)\n \n return f(0)\n\n```\n```python [Tab]\nclass Solution:\n def maximumTotalDamage(self, power: List[int]) -> int:\n freq = defaultdict(int)\n for dmg in power:\n freq[dmg] += 1\n \n unique_power = sorted(freq.keys())\n \n n = len(unique_power)\n dp = [0] * (n + 1)\n \n for i in range(n - 1, -1, -1):\n pick = unique_power[i] * freq[unique_power[i]]\n j = i + 1\n while j < n and (unique_power[j] == unique_power[i] + 1 or unique_power[j] == unique_power[i] + 2):\n j += 1\n if j < n:\n pick += dp[j]\n \n not_pick = dp[i + 1]\n \n dp[i] = max(pick, not_pick)\n \n return dp[0]\n\n```\n```python [Space Opti]\nclass Solution:\n def maximumTotalDamage(self, power: List[int]) -> int:\n freq = defaultdict(int)\n for dmg in power:\n freq[dmg] += 1\n \n unique_power = sorted(freq.keys())\n \n prev2 = prev1 = 0\n \n for dmg in unique_power:\n current = dmg * freq[dmg]\n \n if dmg == unique_power[1] + 1:\n current += prev2\n else:\n current += prev1\n \n prev2 = prev1\n prev1 = current\n \n return max(prev2, prev1)\n\n```\n## TYPESCRIPT / JS:\n```typescript [Memo]\nclass Solution {\n private freq: Map<number, number>;\n private memo: Map<number, number>;\n\n constructor() {\n this.freq = new Map();\n this.memo = new Map();\n }\n\n public maximumTotalDamage(power: number[]): number {\n for (const dmg of power) {\n this.freq.set(dmg, (this.freq.get(dmg) || 0) + 1);\n }\n\n const uniquePower = Array.from(this.freq.keys()).sort((a, b) => a - b);\n\n const f = (ind: number): number => {\n if (ind >= uniquePower.length) return 0;\n if (this.memo.has(ind)) return this.memo.get(ind)!;\n\n let np = f(ind + 1);\n let p = uniquePower[ind] * this.freq.get(uniquePower[ind])!;\n\n if (ind + 1 < uniquePower.length && uniquePower[ind + 1] !== uniquePower[ind] + 1 && uniquePower[ind + 1] !== uniquePower[ind] + 2) {\n p += f(ind + 1);\n } else if (ind + 2 < uniquePower.length && uniquePower[ind + 2] !== uniquePower[ind] + 2) {\n p += f(ind + 2);\n } else if (ind + 3 < uniquePower.length) {\n p += f(ind + 3);\n }\n\n this.memo.set(ind, Math.max(p, np));\n return this.memo.get(ind)!;\n };\n\n return f(0);\n }\n}\n\n```\n```typescript [Tab]\nclass Solution {\n public maximumTotalDamage(power: number[]): number {\n const freq = new Map<number, number>();\n for (const dmg of power) {\n freq.set(dmg, (freq.get(dmg) || 0) + 1);\n }\n\n const uniquePower = Array.from(freq.keys()).sort((a, b) => a - b);\n const n = uniquePower.length;\n const dp: number[] = new Array(n + 1).fill(0);\n\n for (let i = n - 1; i >= 0; --i) {\n let pick = uniquePower[i] * freq.get(uniquePower[i])!;\n let j = i + 1;\n while (j < n && (uniquePower[j] === uniquePower[i] + 1 || uniquePower[j] === uniquePower[i] + 2)) {\n ++j;\n }\n if (j < n) {\n pick += dp[j];\n }\n\n let notPick = dp[i + 1];\n\n dp[i] = Math.max(pick, notPick);\n }\n\n return dp[0];\n }\n}\n```\n```typescript [space opti]\nclass Solution {\n public maximumTotalDamage(power: number[]): number {\n const freq = new Map<number, number>();\n for (const dmg of power) {\n freq.set(dmg, (freq.get(dmg) || 0) + 1);\n }\n\n const uniquePower = Array.from(freq.keys()).sort((a, b) => a - b);\n let prev2 = 0; // dp[i-2]\n let prev1 = 0; // dp[i-1]\n\n for (const dmg of uniquePower) {\n let current = dmg * freq.get(dmg)!;\n\n if (dmg === uniquePower[1] + 1) {\n current += prev2;\n } else {\n current += prev1;\n }\n\n prev2 = prev1;\n prev1 = current;\n }\n\n return Math.max(prev2, prev1);\n }\n}\n\n```\n\n | 2 | 0 | ['Hash Table', 'Dynamic Programming', 'Recursion', 'Memoization', 'Sorting', 'Python', 'C++', 'Java', 'TypeScript'] | 0 |
maximum-total-damage-with-spell-casting | Easy 1D DP [Python, Cpp] Beats 100% | easy-1d-dp-python-cpp-beats-100-by-coder-syuw | \n\n\n\n\n# Intution\nIf we take power[i] we can not take power[i]-2, power[i]-1, power[i]+1, power[i]+2 but we can take all occurences of power[i]\n\nFurthermo | CoderIsCodin | NORMAL | 2024-06-16T10:31:41.639558+00:00 | 2024-09-10T05:16:44.759046+00:00 | 716 | false | \n\n\n\n\n# Intution\nIf we take power[i] we can not take power[i]-2, power[i]-1, power[i]+1, power[i]+2 but we can take all occurences of power[i]\n\nFurthermore if we take max(power) we do not need to check for power[i]+1 and power[i]+2\n\n# Approach 1\nMemoization\n\n# Code\n```\nclass Solution:\n def maximumTotalDamage(self, power: List[int]) -> int:\n \n def rec(ind):\n \n if ind<0: return 0\n if not dp[ind]:\n \n num, freq = cnt[ind]\n take, notTake = num * freq, rec(ind-1)\n pre = ind-1\n while pre>0 and cnt[pre][0] > num-3: pre -= 1\n if cnt[pre][0] < num-2: take += rec(pre)\n \n dp[ind] = max(take, notTake)\n \n return dp[ind]\n \n cnt = sorted(collections.Counter(power).items())\n size = len(cnt)\n dp = [0 for _ in range(size)]\n \n return rec(size-1)\n \n```\n\n# Approach 2\nTabulation\n\n# Code\n```\nclass Solution:\n def maximumTotalDamage(self, power: List[int]) -> int:\n \n cnt = sorted(collections.Counter(power).items())\n size = len(cnt)\n dp = [0 for _ in range(size)]\n dp[0] = cnt[0][0] * cnt[0][1]\n\n for ind in range(1,size):\n num, freq = cnt[ind]\n take, notTake = num * freq, dp[ind-1]\n pre = ind-1\n while pre>0 and cnt[pre][0] > num-3: pre -= 1\n if cnt[pre][0] < num-2: take += dp[pre]\n \n dp[ind] = max(take, notTake)\n \n return dp[size-1]\n \n```\n\n# C++\n```\nclass Solution {\npublic:\n long long maximumTotalDamage(vector<int>& power) {\n \n unordered_map<int,long long> cnt;\n for(auto p:power) cnt[p]++;\n \n vector<int> keys;\n for(auto c:cnt) keys.push_back(c.first);\n sort(keys.begin(), keys.end());\n\n int size = keys.size();\n vector<long long> dp(size);\n dp[0] = keys[0] * cnt[keys[0]];\n\n for(int ind = 1; ind<size; ind++){\n \n long long take = keys[ind] * cnt[keys[ind]], notTake = dp[ind-1];\n int temp = ind-1;\n while(temp>0 && keys[temp] > keys[ind]-3) temp--;\n if(keys[temp] < keys[ind]-2) take += dp[temp];\n \n dp[ind] = max(take, notTake);\n }\n return dp[size-1];\n }\n};\n \n```\n\n | 2 | 0 | ['Dynamic Programming', 'Memoization', 'Python', 'C++', 'Python3'] | 1 |
maximum-total-damage-with-spell-casting | Video Explanation (Optimising solution step by step) O(N*2^N) --> O(N*N* --> O(N*logN) --> O(N) | video-explanation-optimising-solution-st-d8l5 | Explanation\n\nClick here for the video\n\n# Code\n\ntypedef long long int ll;\n\nll dp[100001];\nint nxt[100001];\nint same[100001];\n\nclass Solution {\n \ | codingmohan | NORMAL | 2024-06-16T07:52:26.188348+00:00 | 2024-06-16T07:52:26.188371+00:00 | 105 | false | # Explanation\n\n[Click here for the video](https://youtu.be/o_HVLJSeOEY)\n\n# Code\n```\ntypedef long long int ll;\n\nll dp[100001];\nint nxt[100001];\nint same[100001];\n\nclass Solution {\n \n int n;\n vector<ll> arr;\n \n ll MaxDamage (int i) {\n if (i == n) return 0;\n \n ll &ans = dp[i];\n if (ans != -1) return ans;\n \n ans = max (\n MaxDamage(i+1), \n MaxDamage(nxt[i]) + (same[i] - i)*arr[i]\n ); \n return ans;\n }\n \npublic:\n long long maximumTotalDamage(vector<int>& power) {\n arr.clear();\n n = power.size();\n \n for (auto i : power) arr.push_back(i);\n sort (arr.begin(), arr.end());\n \n int nxt_ind = 0;\n int same_ind = 0;\n \n for (int i = 0; i < n; i ++) {\n while (nxt_ind < n && arr[i]+2 >= arr[nxt_ind]) nxt_ind ++;\n nxt[i] = nxt_ind;\n \n while (same_ind < n && arr[i] == arr[same_ind]) same_ind ++;\n same[i] = same_ind;\n }\n \n memset(dp, -1, sizeof(dp));\n return MaxDamage(0);\n }\n};\n``` | 2 | 0 | ['C++'] | 1 |
maximum-total-damage-with-spell-casting | Binary Search + Dynamic Programming (1D-DP) : 100%BEATS (TIME COMPLEXITY & SPACE COMPLEXITY) | binary-search-dynamic-programming-1d-dp-8lkg1 | Intuition\nWe can select Spell by Power[i]+1,Power[i]-1 ,Power[i]+2,Power[i]-2.\ntherfore Sort the power array and after we only select Power[i]+1 and Power[i]+ | user6155rw | NORMAL | 2024-06-16T06:38:24.513520+00:00 | 2024-06-16T06:38:24.513553+00:00 | 46 | false | # Intuition\nWe can select Spell by Power[i]+1,Power[i]-1 ,Power[i]+2,Power[i]-2.\ntherfore Sort the power array and after we only select Power[i]+1 and Power[i]+2 as we move forward .\n \nuse of upper_bound :\nPower Array have multiple same element then binary search through upper bound and next element is different from Power[i].\ne.g = Power[i]={1,2,2,2,3} and i=1 then apply upper_bound we move to i=4 and ultimately we sumup all number between i=4 to i=1 and then find lower_bound for i-1 as we do upper_bound that\'s why i do i-1 and find power[i]+3 from lower_bound.\n\nuse of lower_bound:\nif we are in ith position then we direct jump to that number position which have power[i]+3 and this index is getting from lower_bound.\ne.g = Power[i]={1,2,4,5,6,7} and i=2 then apply lower_bound for power[i]+3 and we jump to 5th position.\n\n \n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nBinary search + Dynamic Programming(1D-DP) (memoization + tabulation)\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n*logn)\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 : Memoization(TLE)\n```\nclass Solution {\npublic:\n long long max_damage(int index,vector<int>&power,vector<long long>&dp)\n {\n if(index>=power.size())return 0;\n if(dp[index]!=-1)return dp[index];\n int i= upper_bound(power.begin(),power.end(),power[index]) - power.begin();\n int j= lower_bound(power.begin(),power.end(),power[i-1]+3) - power.begin();\n long long take=(power[index]*1LL*(i-index))+max_damage(j,power,dp);\n long long notake = max_damage(index+1,power,dp);\n return dp[index]=max({take,notake});\n }\n long long maximumTotalDamage(vector<int>& power) {\n sort(power.begin(),power.end());\n vector<long long>dp(power.size()+1,-1);\n return max_damage(0,damage,dp);\n }\n};\n```\n# Code : Tabulation\n```\nclass Solution {\npublic:\n long long maximumTotalDamage(vector<int>& power) {\n sort(power.begin(),power.end());\n vector<long long>dp(power.size()+1,0);\n for(int index=power.size()-1;index>=0;index--)\n {\n int i= upper_bound(power.begin(),power.end(),power[index]) - power.begin();\n int j= lower_bound(power.begin(),power.end(),power[i-1]+3) - power.begin();\n long long take=(power[index]*1LL*(i-index))+dp[j];\n long long notake = dp[index+1];\n dp[index]=max(take,notake);\n }\n return dp[0];\n }\n};\n``` | 2 | 0 | ['Binary Search', 'Dynamic Programming', 'C++'] | 0 |
maximum-total-damage-with-spell-casting | 🔥🔥🔥Beats 100% 💯 || JAVA || DP || Memoization || ✅Simple || ✅Clean || ✅Easy to Understand 💯💯💯 | beats-100-java-dp-memoization-simple-cle-u3ta | \n\n\nHere is the Clean, Easy and Fastest Solution for the problem with InDepth Explanation.\nTime Complexity: O(nlogn)\nSpace Complexity: O(n)\n\nIntuition\nTh | anmolmidha | NORMAL | 2024-06-16T06:08:17.044287+00:00 | 2024-06-16T11:03:56.938220+00:00 | 644 | false | \n\n\nHere is the **Clean**, **Easy** and **Fastest** Solution for the problem with **InDepth Explanation**.\nTime Complexity: O(nlogn)\nSpace Complexity: O(n)\n\n**Intuition**\nThe problem requires us to find a subsequence from an array such that the difference between every pair of distinct numbers in the subsequence is more than 2. The goal is to maximize the sum of the subsequence. This suggests that we need to consider each element carefully and decide whether to include it in our subsequence or not.\n\nTo solve this problem, we can use a dynamic programming approach combined with a TreeMap to efficiently handle the elements and their frequencies. The TreeMap helps in maintaining the elements in a sorted order, which allows us to easily navigate and fetch elements that are more than 2 units apart.\n\n**Approach**\n\nInitialization:\nUse a TreeMap to store the frequency of each element in the array, sorted in descending order. This helps in processing the elements from the largest to the smallest.\nInitialize a DP map (dp) to memoize the results for subproblems to avoid redundant computations.\nDynamic Programming Function:\n\nDefine a recursive function maxDamage that computes the maximum sum for the given subsequence criteria.\nBase Condition: If the TreeMap is empty, return 0 (no elements to process).\nMemoization Check: If the result for the current key is already computed, return it from the dp map.\nInclude Current Key:\nCalculate the sum if the current key is included. Multiply the frequency of the current key by the key value.\nAdd the result of recursively calling maxDamage on the map excluding elements within 2 units of the current key.\nExclude Current Key:\nCalculate the sum if the current key is excluded.\nAdd the result of recursively calling maxDamage on the map excluding only the current key.\nStore and Return Result: Store the maximum of the two computed sums in the dp map and return it.\n\n```\nclass Solution {\n public long maximumTotalDamage(int[] power) {\n\n TreeMap<Integer, Integer> treeMp = new TreeMap<>(Comparator.reverseOrder());\n\n for (int i=0; i<power.length; i++) {\n treeMp.put(power[i], treeMp.getOrDefault(power[i], 0)+1);\n }\n\n return maxDamage(treeMp, new HashMap<>());\n }\n\n private long maxDamage(NavigableMap<Integer, Integer> treeMp, Map<Integer, Long> dp) {\n\n // base condition handling, if map is empty return 0;\n if(treeMp.isEmpty()) return 0L;\n\n //fetch current key to be computed\n int key = treeMp.firstKey();\n\n //if we have already computed for current key then simply return the answer\n if(dp.containsKey(key)) return dp.get(key);\n\n // include the current key in computation\n long includePower = (long) treeMp.get(key) * key;\n if(treeMp.ceilingKey(key-3) != null) {\n includePower += maxDamage(treeMp.tailMap(treeMp.ceilingKey(key - 3), true), dp);\n }\n\n // exclude the current key in computation\n long excludePower = 0;\n if(treeMp.ceilingKey(key-1) != null) {\n excludePower += maxDamage(treeMp.tailMap(treeMp.ceilingKey(key-1), true), dp);;\n }\n\n //find the max of the computed cases, store it in dp Map and return\n dp.put(key, Math.max(includePower, excludePower));\n return dp.get(key);\n }\n}\n```\n\n**Explanation of Key Parts**\nTreeMap Construction:\n\nTreeMap<Integer, Integer> treeMp = new TreeMap<>(Comparator.reverseOrder()); initializes the map to store elements in descending order.\nRecursive Function:\n\nThe maxDamage function handles the inclusion and exclusion of elements while ensuring the subsequence condition (difference > 2) is maintained.\nThe use of tailMap with ceilingKey helps in efficiently skipping elements that violate the condition.\nThis approach ensures that we explore all possible subsequences while maintaining efficiency through memoization and sorted data handling using TreeMap\n\n**Hope this explains well**\n**Please Upvote if this has helped :-)** | 2 | 0 | ['Dynamic Programming', 'Tree', 'Java'] | 1 |
maximum-total-damage-with-spell-casting | 🔥 🔥 🔥 Simple Approch | Dp | simple-approch-dp-by-vivek_kumr-o8os | Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem seems to be about calculating the maximum total damage possible using a set | Vivek_kumr | NORMAL | 2024-06-16T04:56:06.016811+00:00 | 2024-06-16T04:56:06.016829+00:00 | 611 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem seems to be about calculating the maximum total damage possible using a set of powers, where each power has a frequency of occurrence. The challenge involves selecting powers such that no two selected powers are within 2 units of each other (due to some implied game mechanics or constraints).\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1.Frequency Calculation:\nFirst, count the frequency of each power level using an unordered map (powerFrequency). This helps in understanding how often each power appears.\n\n2.Sorting Unique Powers:\nExtract unique power levels from powerFrequency into uniquePowers and sort them. Sorting helps in sequential processing and helps when making decisions based on constraints (like ensuring no two selected powers are too close).\n\n3.Dynamic Programming for Maximum Damage:\n-->Use a dynamic programming (DP) approach to calculate the maximum total damage:\n-->Initialize an array maxDamage where maxDamage[i] will store the maximum total damage achievable considering up to the i-th power in uniquePowers.\n-->For each power level in uniquePowers, calculate the potential maximum damage:\n-->Calculate currentDamage as the product of the power level and its frequency (powerFrequency[uniquePowers[i - 1]]).\n-->Calculate takeDamage as currentDamage plus the maximum damage achievable up to the last power level that meets the distance constraint (uniquePowers[i - 1] - uniquePowers[j] > 2).\n-->Update maxDamage[i] as the maximum between takeDamage and maxDamage[i - 1] (the maximum damage without taking the current power level).\n\n4.Return Result:\n-->After iterating through all unique powers, maxDamage[numUniquePowers] will contain the maximum total damage achievable\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n1.O(n log n) due to the sorting step (sort(uniquePowers.begin(), uniquePowers.end())) in the worst case, where n is the number of elements in powers.\n2.The dynamic programming step iterates through uniquePowers and performs constant time operations, resulting in an overall time complexity dominated by the sorting step.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n long long maximumTotalDamage(vector<int>& powers) {\n unordered_map<int, int> powerFrequency;\n for (int power : powers) {\n powerFrequency[power]++;\n }\n vector<int> uniquePowers;\n for (auto& entry : powerFrequency) {\n uniquePowers.push_back(entry.first);\n }\n sort(uniquePowers.begin(), uniquePowers.end());\n int numUniquePowers = uniquePowers.size();\n if (numUniquePowers == 1) {\n return static_cast<long long>(uniquePowers[0]) * powerFrequency[uniquePowers[0]];\n }\n vector<long long> maxDamage(numUniquePowers + 1, 0);\n for (int i = 1; i <= numUniquePowers; ++i) {\n long long currentDamage = static_cast<long long>(uniquePowers[i - 1]) * powerFrequency[uniquePowers[i - 1]];\n long long takeDamage = currentDamage;\n for (int j = i - 2; j >= 0; --j) {\n if (uniquePowers[i - 1] - uniquePowers[j] > 2) {\n takeDamage += maxDamage[j + 1];\n break;\n }\n }\n long long dontTakeDamage = maxDamage[i - 1];\n maxDamage[i] = max(takeDamage, dontTakeDamage);\n }\n return maxDamage[numUniquePowers];\n }\n};\n\n\n``` | 2 | 0 | ['C++'] | 0 |
maximum-total-damage-with-spell-casting | DP beats % | dp-beats-by-mohityadavtx-lbor | Approach\nDP\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n Add your space complexity here, e.g. O(n) \n\n# Code\n\nclass Solution {\n | mohityadavtx | NORMAL | 2024-06-16T04:27:43.637055+00:00 | 2024-06-16T04:27:43.637078+00:00 | 51 | false | # Approach\nDP\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public long maximumTotalDamage(int[] power) {\n \n Arrays.sort(power);\n int n = power.length;\n long dp[][] = new long[n][2];\n dp[0][0] = power[0];\n dp[0][1] = 0;\n long ans = power[0];\n \n for(int i=1;i<n;i++){\n if(power[i] == power[i-1]){\n dp[i][0] = power[i] + dp[i-1][0];\n dp[i][1] = dp[i-1][1];\n ans = Math.max(ans,Math.max(dp[i][1],dp[i][0]));\n continue;\n }\n int offset = 1;\n dp[i][1] = Math.max(dp[i-1][0],dp[i-1][1]);\n while(i-offset >= 0 && power[i] - power[i-offset] <= 2){\n // dp[i][1] = Math.max(dp[i][1],Math.max(dp[i-offset][0],dp[i-offset][1]));\n offset++;\n }\n if(i-offset >= 0){\n dp[i][0] = Math.max(dp[i-offset][1],dp[i-offset][0]) + power[i];\n }\n dp[i][0] = Math.max(dp[i][0],power[i]);\n ans = Math.max(ans,Math.max(dp[i][0],dp[i][1]));\n }\n \n return ans;\n \n }\n}\n``` | 2 | 0 | ['Java'] | 1 |
maximum-total-damage-with-spell-casting | Python Memoization and Bottom-up DP nlogn | python-memoization-and-bottom-up-dp-nlog-n2vf | \n# Memo\n\nclass Solution:\n def maximumTotalDamage_memo(self, power: List[int]) -> int:\n @cache\n def memo(i):\n if i >= n:\n | xleafy | NORMAL | 2024-06-16T04:23:58.723641+00:00 | 2024-06-16T05:11:49.584942+00:00 | 262 | false | \n# Memo\n```\nclass Solution:\n def maximumTotalDamage_memo(self, power: List[int]) -> int:\n @cache\n def memo(i):\n if i >= n:\n return 0\n \n cur = counter[avail[i]] * avail[i]\n res = max(cur, memo(i+1))\n\n if i+3 < n and avail[i+3] - avail[i] > 2:\n res = max(res, memo(i+3) + cur)\n if i+2 < n and avail[i+2] - avail[i] > 2:\n res = max(res, memo(i+2) + cur)\n if i+1 < n and avail[i+1] - avail[i] > 2:\n res = max(res, memo(i+1) + cur)\n \n return res\n \n counter = Counter(power)\n avail = sorted(list(set(power)))\n n = len(avail)\n \n return memo(0)\n\n```\n# Bottom-up\n```\nclass Solution:\n def maximumTotalDamage(self, power: List[int]) -> int:\n counter = Counter(power)\n avail = sorted(list(set(power)))\n n = len(avail)\n\n dp = [0] * n\n res = 0\n\n for i in range(n):\n cur = avail[i] * counter[avail[i]]\n dp[i] = max(res, cur)\n\n if i - 3 >= 0:\n dp[i] = max(dp[i], dp[i-3] + cur)\n if i - 2 >= 0 and avail[i] - avail[i-2] > 2:\n dp[i] = max(dp[i], dp[i-2] + cur)\n if i - 1 >= 0 and avail[i] - avail[i-1] > 2:\n dp[i] = max(dp[i], dp[i-1] + cur)\n\n res= max(res, dp[i])\n return res\n\n``` | 2 | 0 | ['Dynamic Programming', 'Memoization', 'Python3'] | 0 |
maximum-total-damage-with-spell-casting | Both Top-Down and Bottom-Up | both-top-down-and-bottom-up-by-mikposp-pb7n | Code #1 - Top-Down\nTime complexity: O(nlog(n)). Space complexity: O(n).\n\nclass Solution:\n def maximumTotalDamage(self, a: List[int]) -> int:\n c = | MikPosp | NORMAL | 2024-06-16T04:12:57.498481+00:00 | 2024-06-20T22:30:43.262825+00:00 | 255 | false | # Code #1 - Top-Down\nTime complexity: $$O(n*log(n))$$. Space complexity: $$O(n)$$.\n```\nclass Solution:\n def maximumTotalDamage(self, a: List[int]) -> int:\n c = sorted(Counter(a).items())\n \n @cache\n def calc(i):\n res1 = i+1 < len(c) and calc(i+1)\n res2 = c[i][0]*c[i][1]\n if i+1 < len(c) and c[i+1][0]-c[i][0] > 2:\n res2 += calc(i+1)\n elif i+2 < len(c) and c[i+2][0]-c[i][0] > 2:\n res2 += calc(i+2)\n elif i+3 < len(c):\n res2 += calc(i+3)\n \n return max(res1, res2)\n \n return max(calc(i) for i in range(min(len(c), 3)))\n```\n\n# Code #2 - Bottom-Up\nTime complexity: $$O(n*log(n))$$. Space complexity: $$O(n)$$.\n```\nclass Solution:\n def maximumTotalDamage(self, a: List[int]) -> int:\n c = [[0,0], [0,0], [0,0]] + sorted(map(list, Counter(a).items()))\n for i in range(3, len(c)):\n c[i][1] = max(\n c[i-1][1] + (c[i][0] - c[i-1][0] > 2)*c[i][0]*c[i][1],\n c[i-2][1] + (c[i][0] - c[i-2][0] > 2)*c[i][0]*c[i][1],\n c[i-3][1] + c[i][0]*c[i][1]\n )\n\n return max(c[-3:], key=itemgetter(1))[1]\n``` | 2 | 0 | ['Dynamic Programming', 'Recursion', 'Memoization', 'Sorting', 'Python', 'Python3'] | 0 |
maximum-total-damage-with-spell-casting | exactly similar code to delete and earn | exactly-similar-code-to-delete-and-earn-3d8cn | IntuitionIn delete and earn problem we have to skip only i-1 and i+1 elements(Moreover we just need to skip i+1 element because sorting will help us in getting | ram_bhakt123 | NORMAL | 2025-02-19T07:47:18.661800+00:00 | 2025-02-19T07:57:12.598289+00:00 | 32 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
In delete and earn problem we have to skip only i-1 and i+1 elements(Moreover we just need to skip i+1 element because sorting will help us in getting rid of i-1 element). And in this problem we have to skip i-1, i-2, i+1, i+2 elements(again we just have to skip i+1 and i+2 element because sorting will help us in getting rid of i-1 and i-2 element).
delete and earn code
https://leetcode.com/problems/delete-and-earn/solutions/6441150/easiest-code-by-ram_bhakt123-ounz/
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
long long rec(vector<int>& power,int i){
if(i>=power.size()){
return 0;
}
long long currVal=power[i];
long long currSum=power[i];
long long index=i+1;
// while it is the same as the current value, include in our sum
while(index<power.size() && power[index]==currVal){
currSum+=currVal;
index++;
}
// skip all the elements, whose value is equal to curVal+1 or curVal+2
while(index<power.size() && (power[index]==currVal+1 || power[index]==currVal+2)){
index++;
}
// so if we decided to pick the element, then upto the element
// we skip the nums[i]+1 or nums[i]+2 value, we pass that index
// otherwise simply pass i+1.
long long pick=currSum+rec(power,index);
long long not_pick=rec(power,i+1);
return max(pick,not_pick);
}
long long topdown(vector<int>& power,int i,vector<long long>& dp){
if(i>=power.size()){
return 0;
}
if(dp[i]!=-1){
return dp[i];
}
long long currVal=power[i];
long long currSum=power[i];
long long index=i+1;
// while it is the same as the current value, include in our sum
while(index<power.size() && power[index]==currVal){
currSum+=currVal;
index++;
}
// skip all the elements, whose value is equal to curVal+1 or curVal+2
while(index<power.size() && (power[index]==currVal+1 || power[index]==currVal+2)){
index++;
}
// so if we decided to pick the element, then upto the element
// we skip the nums[i]+1 value, we pass that index
// otherwise simply pass i+1.
long long pick=currSum+topdown(power,index,dp);
long long not_pick=topdown(power,i+1,dp);
return dp[i]=max(pick,not_pick);
}
long long bottomup(vector<int>& power){
int n=power.size();
vector<long long>dp(n+1,-1);
dp[n]=0;
for(int i=n-1;i>=0;i--){
long long currVal=power[i];
long long currSum=power[i];
long long index=i+1;
// while it is the same as the current value, include in our sum
while(index<power.size() && power[index]==currVal){
currSum+=currVal;
index++;
}
// skip all the elements, whose value is equal to curVa1+1 or curVal+2
while(index<power.size() && (power[index]==currVal+1 || power[index]==currVal+2)){
index++;
}
// so if we decided to pick the element, then upto the element
// we skip the nums[i]+1 value, we pass that index
// otherwise simply pass i+1.
long long pick=currSum+dp[index];
long long not_pick=dp[i+1];
dp[i]=max(pick,not_pick);
}
return dp[0];
}
long long optimised(vector<int>& power){
map<int, long long>freq;
for(auto p:power){
freq[p]+=p;
}
vector<int>unique_power;
for(auto& [key,val]:freq){
unique_power.push_back(key);
}
int n=unique_power.size();
vector<long long >dp(n+1,-1);
dp[n]=0;
for(int i=n-1;i>=0;i--){
long long pick=freq[unique_power[i]];
int nextIndex=upper_bound(unique_power.begin()+i+1,unique_power.end(),unique_power[i]+2)-unique_power.begin();
pick+=dp[nextIndex];
long long not_pick=dp[i+1];
dp[i]=max(pick,not_pick);
}
return dp[0];
}
long long maximumTotalDamage(vector<int>& power) {
// int n=power.size();
// sort(power.begin(),power.end());
// return rec(power,0);
// vector<long long>dp(n+1,-1);
// return topdown(power,0,dp);
// return bottomup(power);
return optimised(power);
}
};
``` | 1 | 0 | ['Hash Table', 'Binary Search', 'Dynamic Programming', 'Sorting', 'C++'] | 0 |
maximum-total-damage-with-spell-casting | Easy Iterative Dp | easy-iterative-dp-by-kvivekcodes-duwj | 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 | kvivekcodes | NORMAL | 2024-07-05T10:00:30.654066+00:00 | 2024-07-05T10:00:30.654099+00:00 | 8 | 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 long long maximumTotalDamage(vector<int>& power) {\n map<int, long long> mp;\n for(auto it: power) mp[it] += it;\n int n = mp.size();\n vector<int> cnt;\n for(auto it: mp) cnt.push_back(it.first);\n\n long long ans = 0;\n\n vector<long long> dp(n, 0);\n for(int i = 0; i < n; i++){\n int num = cnt[i];\n auto it = lower_bound(cnt.begin(), cnt.end(), num-2) - cnt.begin();\n if(cnt[it] > num-2) it--;\n if(it >= 0) dp[i] = max(dp[i], dp[it]);\n\n auto it2 = lower_bound(cnt.begin(), cnt.end(), num-3) - cnt.begin();\n if(cnt[it2] > num-3) it2--;\n if(it2 < 0) dp[i] = max(dp[i], mp[num]);\n else dp[i] = max(dp[i], mp[num] + dp[it2]);\n\n ans = max(ans, dp[i]);\n if(i > 0) dp[i] = max(dp[i], dp[i-1]);\n }\n for(int i = 0; i < n; i++){\n cout << dp[i] << \' \';\n }\n cout << endl;\n return ans;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
maximum-total-damage-with-spell-casting | Python 3 DP+Binary Search solution | python-3-dpbinary-search-solution-by-sai-ne2o | 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 | saisanjith15 | NORMAL | 2024-06-20T17:41:50.740176+00:00 | 2024-06-20T17:41:50.740237+00:00 | 15 | 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: O(nlogn)\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```\nfrom collections import defaultdict\nclass Solution:\n def maximumTotalDamage(self, power: List[int]) -> int:\n hashMap = defaultdict(int)\n for i in range(len(power)):\n hashMap[power[i]]+=1\n spells = [[float(\'-inf\'),0]]\n for i in hashMap.keys():\n spells.append([i,hashMap[i]])\n spells.sort()\n n = len(spells)\n dp = [0]*n\n for i in range(1,n):\n l=0\n h=i\n maxDamage = 0\n while l <= h:\n mid = (l+h)//2\n if spells[mid][0] <= spells[i][0] - 3:\n maxDamage = max(maxDamage,dp[mid])\n l = mid+1\n else:\n h = mid-1\n dp[i]=max(dp[i-1],maxDamage+spells[i][1]*spells[i][0])\n return max(dp)\n \n\n \n\n\n \n``` | 1 | 0 | ['Hash Table', 'Binary Search', 'Dynamic Programming', 'Sorting', 'Python3'] | 0 |
maximum-total-damage-with-spell-casting | Recursion + memoization DP(Pick and Non Pick concept) with TC : O(n) , SC : O(n) | recursion-memoization-dppick-and-non-pic-si54 | \nclass Solution {\npublic:\n \n long long helper(vector<pair<long long,long long>> &count,vector<long long> &dp,int idx,long long prev){\n if(idx> | adithya_u_bhat | NORMAL | 2024-06-20T11:25:29.235561+00:00 | 2024-06-20T11:28:32.035115+00:00 | 95 | false | ```\nclass Solution {\npublic:\n \n long long helper(vector<pair<long long,long long>> &count,vector<long long> &dp,int idx,long long prev){\n if(idx>=count.size()){\n return 0;\n }\n if(dp[idx]!=-1){\n return dp[idx];\n }\n long long nonPick = helper(count,dp,idx+1,prev);\n pair<long long,long long> val = count[idx];\n long long add = 0;\n if(idx+1<count.size()){\n if(count[idx+1].first==val.first+1 || count[idx+1].first==val.first+2){\n add++;\n }\n }\n if(idx+2<count.size()){\n if(count[idx+2].first==val.first+1 || count[idx+2].first==val.first+2){\n add++;\n }\n }\n long long pick = val.first*val.second+helper(count,dp,idx+add+1,val.first);\n return dp[idx] = max(pick,nonPick);\n \n \n }\n long long maximumTotalDamage(vector<int>& power) {\n int n = power.size();\n map<long long,long long> mp;\n for(int i=0;i<n;i++){\n mp[power[i]]++;\n }\n vector<pair<long long,long long>> count;\n vector<long long> dp(1e5,-1);\n for(auto it:mp){\n count.push_back({it.first,it.second});\n }\n return helper(count,dp,0,-10);\n }\n};\n``` | 1 | 0 | [] | 0 |
maximum-total-damage-with-spell-casting | 🔥Simple and efficient approach using DP | simple-and-efficient-approach-using-dp-b-4snq | 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 | Sparsh_7637 | NORMAL | 2024-06-19T08:56:53.461242+00:00 | 2024-06-19T08:56:53.461310+00:00 | 62 | 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 $$O(n)$$\n\n- Space complexity:\n$$O(n)$$ \n\n# Code\n```\nclass Solution {\npublic:\n long long func(vector<long long>& dp, vector<int>& v, map<int,long long>& m, int ind) {\n int n = v.size();\n if (ind >= n) return 0;\n if (dp[ind] != -1) return dp[ind];\n\n long long ans = func(dp, v, m, ind + 1);\n\n for (int i = 1; i <= 3; i++) {\n if (ind+i<n and v[ind+i] - v[ind] >= 3) {\n ans = max(ans, v[ind] * m[v[ind]] + func(dp, v, m, ind+i));\n break;\n }\n }\n\n return dp[ind] = max(ans, v[ind] * m[v[ind]]);\n }\n\n long long maximumTotalDamage(vector<int>& p) {\n map<int, long long> m;\n for (auto it : p) m[it]++;\n vector<int> v;\n for (auto it : m) v.push_back(it.first);\n int n = v.size();\n vector<long long> dp(n + 1, -1);\n return func(dp, v, m, 0);\n }\n};\n\n``` | 1 | 0 | ['C++'] | 0 |
maximum-total-damage-with-spell-casting | DP || Memoization || Previous Element Trick || 2D DP || o(n) | dp-memoization-previous-element-trick-2d-k34p | Intuition\nTake and not take elements. DP based on previous element.\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nCreating a new | KVNS07 | NORMAL | 2024-06-17T20:27:50.485553+00:00 | 2024-06-17T20:27:50.485587+00:00 | 38 | false | # Intuition\nTake and not take elements. DP based on previous element.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nCreating a new unique element array a.\nCreating frequency array b of the elements.\n\nInstead of using index and previous element for memoization.\nTaking 2d DP with variables "index" and "state of previous element".\n0: if previous element is lesser than a[i]-2\n1: if previous element is equal to a[i]-2\n2: if previous element is equal to a[i]-1\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n- o(n) as max 100000x3... nx3\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 long long fun(int i,vector<long long>&a,vector<long long>&b,int prev,vector<vector<long long>>&dp){\n if(i==a.size()) return 0;\n long long ans=0;\n int fl=-1;\n if(a[i]==prev+2)fl=1;\n else if(a[i]==prev+1) fl=2;\n else fl=0;\n if(dp[i][fl]!=-1) {return dp[i][fl];}\n \n if(a[i]>prev+2) {ans=fun(i+1,a,b,a[i],dp)+a[i]*b[i];}\n ans=max(ans,fun(i+1,a,b,prev,dp));\n return dp[i][fl]=ans;\n }\n long long maximumTotalDamage(vector<int>& power) {\n vector<vector<long long>>dp(power.size(),vector<long long>(3,-1));\n unordered_map<int,int> mp;\n for(int i=0;i<power.size();i++) mp[power[i]]++;\n vector<long long> a,b;\n for(auto i:mp) a.push_back(i.first);\n sort(a.begin(),a.end());\n for(auto i:a) b.push_back(mp[i]);\n return fun(0,a,b,-3,dp);\n }\n};\n``` | 1 | 0 | ['Dynamic Programming', 'C++'] | 1 |
maximum-total-damage-with-spell-casting | Beats 100% in Space/ Memory, Knapsack - like, C++ | beats-100-in-space-memory-knapsack-like-dj0a1 | Intuition\n Describe your first thoughts on how to solve this problem. I\'ve seen a similar problem before on LeetCode.\n# Approach\n1. Sort the array, so that | anchalbajpai | NORMAL | 2024-06-17T11:17:08.532997+00:00 | 2024-06-17T11:20:01.516317+00:00 | 216 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->I\'ve seen a similar problem before on LeetCode.\n# Approach\n1. Sort the array, so that you don\'t have to care about the `power[i]-2` and `power[i]-1` thing.\n\n2. Follow the basic include/exclude approach as in case of bounded knapsack.\n\n3. Once you choose a certain `power[i]` you should choose all the moves with damage `power[i]` , for e.g. in `[1,2,2,2,3]` if we are at index `1` (in 0 - based indexing) then all moves `j` with `power[j] == 2` must be chosen at once ( here, their collected damage is stored in `dmg` variable ), you can also use map for storing counts of all the moves.\n\n4. You can either choose a move, getting `dmg` damage, skipping all indices with damages `power[i]+1` and `power[i]+2`, and proceed with index `i2`, or you can choose to not include any of the indices `j` with `power[j] == power[i]`, and start with the next index `i1`. \n\n# Complexity\n- Time complexity:\n**O(nlog(n))** // because sorting\n\n- Space complexity:\n**O(n)** **+ Auxiliary Stack Space due to recursion.**\n\n# Code\n```\nclass Solution {\npublic:\n long long dp[100005];\n long long solveRec(int ind, vector<int>& p) {\n\n if (ind == p.size())\n return 0;\n if (dp[ind] != -1)\n return dp[ind];\n long long dmg = 0;\n int i = ind;\n while (i < p.size() && p[i] == p[ind])\n dmg += p[i++];\n int i1 = i;\n\n while (i < p.size() && p[i] == p[ind] + 1)\n i++;\n while (i < p.size() && p[i] == p[ind] + 2)\n i++;\n int i2 = i;\n\n return dp[ind] = max(dmg + solveRec(i2, p), solveRec(i1, p));\n }\n\npublic:\n long long maximumTotalDamage(vector<int>& p) {\n sort(p.begin(), p.end());\n memset(dp, -1, sizeof dp);\n return solveRec(0, p);\n }\n};\n``` | 1 | 0 | ['Dynamic Programming', 'Recursion', 'C++'] | 1 |
maximum-total-damage-with-spell-casting | No Binary Search (Upper Bound, LowerBound) | Map | Maximum Total Damage With Spell | Easy C++ | no-binary-search-upper-bound-lowerbound-0tp08 | \n# Complexity\n- Time complexity:O(nlogn) : O(n)\ dp + nlogn \ Array \ creation \n Add your time complexity here, e.g. O(n) \n\n- Space complexity:O(n)\n Add y | JeetuGupta | NORMAL | 2024-06-17T06:39:01.651088+00:00 | 2024-06-17T06:39:01.651123+00:00 | 31 | false | \n# Complexity\n- Time complexity:$$O(nlogn) : O(n)\\ dp + nlogn \\ Array \\ creation$$ \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 long long helper(vector<pair<int, int>> &nums, int i, vector<long long> &memo){\n if(i == nums.size()) return 0;\n\n if(memo[i] != -1) return memo[i];\n\n long long take = (long long)nums[i].first * nums[i].second;\n if(i + 1 < nums.size() && nums[i].first + 2 < nums[i+1].first){\n take += helper(nums, i+1, memo);\n }else if(i + 2 < nums.size() && nums[i].first + 2 < nums[i+2].first){\n take += helper(nums, i+2, memo);\n }else if(i + 3 < nums.size()){\n take += helper(nums, i+3, memo);\n }\n\n long long notTake = helper(nums, i + 1, memo);\n \n return memo[i] = max(take, notTake);\n }\n long long maximumTotalDamage(vector<int>& power) {\n map<int, int> mp;\n for(auto x : power){\n mp[x]++;\n }\n vector<pair<int, int>> nums(mp.size());\n int i = 0;\n for(auto &x : mp){\n nums[i] = {x.first, x.second};\n i++;\n }\n vector<long long> memo(mp.size(), -1);\n return helper(nums, 0, memo);\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
maximum-total-damage-with-spell-casting | Tabulataion || C++ | tabulataion-c-by-bhanunegi420-9exl | Intuition\nWe\'ll make a dp array that will store the previous answers of wether taking the element or not. If taken we will take the max element that we can ta | bhanunegi420 | NORMAL | 2024-06-17T02:37:17.271253+00:00 | 2024-06-17T02:37:17.271272+00:00 | 5 | false | # Intuition\nWe\'ll make a dp array that will store the previous answers of wether taking the element or not. If taken we will take the max element that we can take in the array. Sort the array and take the frequency map of the array in order to reduce operations and if we take that element we will take all its occurances.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\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 \n //Tabulation trying\n long long maximumTotalDamage(vector<int>& powers) {\n ios_base::sync_with_stdio(false);\n cin.tie(NULL); cout.tie(NULL);\n unordered_map<int, int> mp;\n for (auto it : powers) {\n mp[it]++;\n }\n\n vector<int> arr;\n for (auto it = mp.begin(); it != mp.end(); it++) {\n arr.push_back(it->first);\n }\n sort(arr.begin(), arr.end());\n\n int n = arr.size();\n if (n == 1) {\n long long ans = static_cast<long long>(arr[0]) * mp[arr[0]];\n return ans;\n }\n\n vector<long long> dp(n + 1, 0);\n for (int i = 1; i <= n; i++) {\n long long curr = static_cast<long long>(arr[i - 1]) * mp[arr[i - 1]];\n long long take = curr;\n\n for (int j = i - 2; j >= 0; j--) {\n if (arr[i - 1] - arr[j] > 2) {\n take += dp[j + 1];\n break;\n }\n }\n\n long long nottake = dp[i - 1];\n dp[i] = max(take, nottake);\n }\n\n return dp[n];\n }\n};\n\n``` | 1 | 0 | ['Dynamic Programming', 'Greedy', 'C++'] | 0 |
maximum-total-damage-with-spell-casting | O(N) Solution(java) | using dynamic programming | on-solutionjava-using-dynamic-programmin-55lb | Intuition\n Describe your first thoughts on how to solve this problem. \nSimilar to house robber with slight modification\n\n# Approach\ncalculate freqency\nget | rishipebbeti | NORMAL | 2024-06-16T18:06:07.159414+00:00 | 2024-06-16T18:06:07.159443+00:00 | 58 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSimilar to house robber with slight modification\n\n# Approach\ncalculate freqency\nget unique powers\nsort unique powers\ndo dp similar to house robber problem, ignore values bw pow[i-2] and pow[i]\n<!-- Describe your approach to solving the problem. -->\n\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 {\n public long maximumTotalDamage(int[] power) {\n int n = power.length;\n Map<Integer, Integer> freq = new HashMap<>();\n for(int p: power)\n freq.put(p, freq.getOrDefault(p, 0)+1);\n int s = freq.size();\n int unqPow[] = new int[s];\n int i=0;\n for(int key: freq.keySet()) \n unqPow[i++] = key;\n Arrays.sort(unqPow);\n long dp[] = new long[s];\n dp[0] = (long)unqPow[0] * freq.get(unqPow[0]);\n for(i=1; i<s;i++){\n dp[i] = dp[i-1];\n long curPower = unqPow[i] * freq.get(unqPow[i]);\n long curTotalPower = curPower;\n for(int j = i-1; j>=0 && j>=i-3;j--){\n if(unqPow[j] < unqPow[i]-2){\n curTotalPower = Math.max(curTotalPower, curPower + dp[j]);\n }\n }\n dp[i] = Math.max(dp[i], curTotalPower);\n }\n return dp[s-1];\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
maximum-total-damage-with-spell-casting | EASY DP | easy-dp-by-tin_le-6xd7 | 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 | tin_le | NORMAL | 2024-06-16T16:35:06.156318+00:00 | 2024-06-16T16:36:49.836929+00:00 | 76 | 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 long long maximumTotalDamage(vector<int>& power) {\n unordered_map<int, int> mp;\n for(auto& num : power) mp[num]++;\n long long res = 0;\n sort(power.begin(), power.end());\n power.erase(unique(power.begin(), power.end()), power.end());\n int n = power.size();\n long long dp[100001] = {};\n long long maxi = 0;\n for(int i = 0, j = 0; i < n; i++)\n {\n while(power[j] < power[i] - 2) // we want the value less than current power - 2 only\n {\n maxi = max(maxi, dp[j++]);\n }\n dp[i] = (long long)power[i] * mp[power[i]] + maxi;\n res = max(res, dp[i]);\n }\n return res;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
maximum-total-damage-with-spell-casting | [CPP] Beats 100% || Detailed Intuition Given in Comments || HashMap || DP | cpp-beats-100-detailed-intuition-given-i-p97s | Intuition & Approach\nDescribe in the Code Comments step by step.\n\n# Complexity\n- Time complexity: O(N LogN) Because of sorting and in the for loop, the coll | Phoenix754 | NORMAL | 2024-06-16T11:19:30.637500+00:00 | 2024-06-16T11:19:30.637521+00:00 | 81 | false | # Intuition & Approach\nDescribe in the Code Comments step by step.\n\n# Complexity\n- **Time complexity**: $$O(N LogN)$$ Because of sorting and in the for loop, the colliding spells are atmost 2 if present. As we are taking unique values so the colliding spells occurs only once in the array. So the for loop is taking $$O(N)$$ time. Hence the overall time comlexity would be $$O(NlogN)$$.\n\n- **Space complexity**: $$O(3N)$$ for hashMap, Vector and DP array.\n\n# Code\n```\nclass Solution {\npublic:\n long long maximumTotalDamage(vector<int>& power) {\n\n // Step1: Get the frequencies of each spells\n unordered_map<int,int> spellFreq;\n for(int it : power) {\n spellFreq[it]++;\n }\n\n // Step2: Collect the unique spells\n vector<long long> uniqueSpell;\n for(auto it : spellFreq) {\n uniqueSpell.push_back(it.first);\n }\n\n // Step3 : Sort the unique spells so that we can get increasing order of\n // damage. Beacuse while we are moving backwards to find the non-colliding spell\n // we need to ensure the closest values should appear. Take the example\n // [7,1,6] while we are traversing back for the non-colliding spell upon\n // reaching 1 we will find that and stop, but 7 is there which will collide\n sort(uniqueSpell.begin(), uniqueSpell.end());\n\n // Create a DP array of size uniqueSpell\n int totaluniqueSpell = uniqueSpell.size();\n vector<long long> maxDamageDp(totaluniqueSpell, 0);\n\n // Initialize the Dp array with first spell\n // because dp[i] represents the max damage acheivabale\n // using the first unique i spells.\n // so for 0th index the max possible damage is itself * freq of it\n maxDamageDp[0] = uniqueSpell[0] * spellFreq[uniqueSpell[0]];\n\n // Step4: Traverse through the unique spells\n for(int i = 1; i < totaluniqueSpell; i++) {\n\n // Step5: Get the current spell damage and the total damage\n // possible with that spell\n long long currentDamage = uniqueSpell[i];\n long long totalCurrentDamage = currentDamage * spellFreq[currentDamage];\n\n // Assuming that current spell is not used\n maxDamageDp[i] = maxDamageDp[i-1];\n\n // Step6: Until a spell found that don\'t collide with the current\n // go backwards. As we have done sorting so we only search for less damage spells.\n int prevInd = i-1;\n while (prevInd >= 0 && (uniqueSpell[prevInd] == currentDamage - 1 || uniqueSpell[prevInd] == currentDamage - 2)) {\n prevInd--;\n }\n\n // Step7: A Spell found that don\'t collide with the current Spell or\n // there is no spell [prevInd == -1]\n // if A spell is found then we need to take the maximum among the\n // current value (we initialize the current dp state with prevind value)\n // and the sum of totalCurrentDamage and previous valid dp state value\n // (maximum value upto a non-colliding spell)\n if(prevInd >= 0) {\n maxDamageDp[i] = max(maxDamageDp[i], maxDamageDp[prevInd] + totalCurrentDamage);\n }\n\n // If all spells are colliding then take the maximum of only the current\n // and the prevstate which is already in the maxDamageDp[i]\n else {\n maxDamageDp[i] = max(maxDamageDp[i], totalCurrentDamage);\n }\n }\n return maxDamageDp[totaluniqueSpell-1];\n }\n};\n``` | 1 | 0 | ['Hash Table', 'Dynamic Programming', 'Sorting', 'C++'] | 0 |
maximum-total-damage-with-spell-casting | Java DP+Map -> From Recursion to Optimised | java-dpmap-from-recursion-to-optimised-b-ah0m | Intuition\nPick and Not pick pattern is used after sorting the given array. A simple condition is added to check if the next incoming element is greater than th | shapunk | NORMAL | 2024-06-16T08:01:14.470174+00:00 | 2024-06-16T08:02:14.125500+00:00 | 101 | false | # Intuition\nPick and Not pick pattern is used after sorting the given array. A simple condition is added to check if the next incoming element is greater than the (given element + 2);\n# Approach\n1. Sort the array\n2. Then in the recursive call, use pick and not pick pattern.\n3. When picking add all the duplicates and make sure to find the next index which fulfills the given condition. \n4. Return max of pick and not pick.\n# Complexity\n- Time complexity: O(2^n)\n\n- Space complexity: O(n) -> recursive stack\n\n# Code\n```\nclass Solution {\n public long helper(int[] power, int i){\n if(i>=power.length){\n return 0;\n }\n long notPick = helper(power, i+1);\n long pick = power[i];\n int newI = i+1;\n while(newI<power.length && power[newI]==power[i]){\n pick += power[i];\n newI++;\n }\n while(newI<power.length && power[newI]<=power[i]+2){\n newI++;\n }\n pick += helper(power, newI);\n\n return Math.max(pick, notPick);\n\n }\n public long maximumTotalDamage(int[] power) {\n Arrays.sort(power);\n return helper(power, 0);\n }\n}\n```\n\nThis solution will give TLE (Obviously).\n\n# DP Optimisation\n\nThe previous solution can be optimised using memoisation.\nMake a dp array and store the index i results in it.\n\n\n# Complexity\n- Time complexity: \uD835\uDC42(n^2).\n\n- Space complexity: O(n) -> recursive stack\n\n```\nCode block\nclass Solution {\n public long helper(int[] power, int i, long[] dp){\n if(i>=power.length){\n return 0;\n }\n if(dp[i]!=-1){\n return dp[i];\n }\n long notPick = helper(power, i+1, dp);\n long pick = power[i];\n int newI = i+1;\n while(newI<power.length && power[newI]==power[i]){\n pick += power[i];\n newI++;\n }\n while(newI<power.length && power[newI]<=power[i]+2){\n newI++;\n }\n pick += helper(power, newI, dp);\n\n return dp[i]=Math.max(pick, notPick);\n }\n public long maximumTotalDamage(int[] power) {\n Arrays.sort(power);\n long[] dp = new long[power.length+1];\n Arrays.fill(dp, -1);\n return helper(power, 0, dp);\n }\n}\n```\n \n# Further optimisation -> DP + MAP\n\nDuplicates can be stored in a map to reduce the time complexity involved.\n\n# Complexity\nTaking m as the size of unique powers.\n- Time complexity: \uD835\uDC42(m^2).\n\n- Space complexity: O(m) -> recursive stack\n```\nCode block\nclass Solution {\n public long helper(int[] power, int i, long[] dp, Map<Integer, Integer> count) {\n if (i >= power.length) {\n return 0;\n }\n if (dp[i] != -1) {\n return dp[i];\n }\n long notPick = helper(power, i + 1, dp, count);\n long pick = (long) power[i] * count.get(power[i]);\n int newI = i + 1;\n while (newI < power.length && power[newI] <= power[i] + 2) {\n newI++;\n }\n pick += helper(power, newI, dp, count);\n\n return dp[i] = Math.max(pick, notPick);\n }\n\n public long maximumTotalDamage(int[] power) {\n Map<Integer, Integer> count = new HashMap<>();\n for (int num : power) {\n count.put(num, count.getOrDefault(num, 0) + 1);\n }\n int[] newPower = count.keySet().stream().mapToInt(Integer::intValue).toArray();\n Arrays.sort(newPower);\n\n long[] dp = new long[power.length + 1];\n Arrays.fill(dp, -1);\n return helper(newPower, 0, dp, count);\n }\n}\n``` | 1 | 0 | ['Hash Table', 'Dynamic Programming', 'Ordered Map', 'Sorting', 'Java'] | 2 |
maximum-total-damage-with-spell-casting | Don't know how to optimize ? | 100% beats | java | dont-know-how-to-optimize-100-beats-java-9ux2 | \nSort the array to find A[i]+1 A[i]-1 A[i]+2 A[i]-2 easily\n\n### Approach 1 \nnaive DP would be to keep dp[i][j] that stores maximum damage for subarray i..j | Nagaraj_Poojari | NORMAL | 2024-06-16T07:41:37.096177+00:00 | 2024-06-16T07:41:37.096226+00:00 | 131 | false | \nSort the array to find `A[i]+1` `A[i]-1` `A[i]+2` `A[i]-2` easily\n\n### Approach 1 \nnaive DP would be to keep `dp[i][j]` that stores maximum damage for subarray `i..j`.\nThen for every `mid` call for subproblems on left and right side.\nex : \nA=[1,1,1,<ins> 2,2,4,5,5,5 </ins> ,8,9,10]\n```\nlets mid = 5 ,// A[mid]=5\ncall for f(0,2) and f(9,11)\n```\nTime complexity would be `O(n^3)`\n\n### Approach 2\n\nAt a time only consider solutions of `0..i` , then you can easily ignore `A[i]+1 ` `A[i]+2` conditions.\nYou can go with\nlinear search to find left most index `O(n^2)`\nBinary seach as array is sorted `O(nlogn)`\nHashMap to store first encountered index `O(n)`\n\nFor below HashMap code , TC : `O(nlogn + O(n))`\n\n# Code\n```\nclass Solution {\n public long maximumTotalDamage(int[] A) {\n int n=A.length;\n long[] dp=new long[n];\n Arrays.sort(A);\n Map<Integer,Integer> map=new HashMap<>();\n long res=0l;\n \n for(int i=0;i<n;i++){\n long score= 0l;\n int left=Math.min(map.getOrDefault(A[i]-1,i) , map.getOrDefault(A[i]-2,i));\n left=Math.min(left, map.getOrDefault(A[i],i));\n score=((long)(i- map.getOrDefault(A[i],i) + 1))*A[i];\n \n score+=left>0 ? dp[left-1]:0;\n dp[i]=Math.max(i>0 ? dp[i-1]:0 , score);\n\n map.putIfAbsent(A[i],i);\n }\n return dp[n-1];\n }\n \n \n}\n``` | 1 | 0 | ['Hash Table', 'Dynamic Programming', 'Sorting', 'Heap (Priority Queue)', 'Java'] | 0 |
maximum-total-damage-with-spell-casting | DP || Memoization || ✅Clean & Easy to understand💯 | dp-memoization-clean-easy-to-understand-282t8 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n1-Storing the frequency of elements in a map to process the condition for | DivyenduVimal | NORMAL | 2024-06-16T06:52:06.028498+00:00 | 2024-06-16T06:52:06.028528+00:00 | 165 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1-Storing the frequency of elements in a map to process the condition for equal elements.\n2-Storing thee unique values int the vector v and the applying pick and not pick and then taking maximum among them.\n\n# Complexity\n- Time complexity:\nO(n)\n- Space complexity:\nO(n)\n\n# Code\n```\nusing ll=long long;\nclass Solution {\n map<ll,ll> m;\n ll dp[100001];\n long long solve(int i,vector<long long>& v)\n { \n if(i>=v.size())\n {\n return 0;\n }\n if(dp[i]!=-1)\n {\n return dp[i];\n }\n long long not_take=0,take=0;\n if(i+1<v.size() && v[i+1]>v[i]+2)\n {\n take=(v[i]*m[v[i]])+solve(i+1,v);\n }\n else if(i+2<v.size() && v[i+2]>v[i]+2)\n {\n take=(v[i]*m[v[i]])+solve(i+2,v); \n }\n else\n {\n take=(v[i]*m[v[i]])+solve(i+3,v); \n }\n not_take=solve(i+1,v);\n return dp[i]=max<ll>(take,not_take);\n }\npublic:\n long long maximumTotalDamage(vector<int>& power) {\n vector<long long> v;\n m.clear();\n for(int i=0;i<power.size();i++)\n {\n if(m[power[i]]==0)\n {\n v.push_back(power[i]);\n }\n m[power[i]]++;\n }\n sort(v.begin(),v.end());\n memset(dp,-1,sizeof(dp));\n return solve(0,v);\n }\n};\n``` | 1 | 0 | ['Hash Table', 'Dynamic Programming', 'Memoization', 'C++'] | 0 |
maximum-total-damage-with-spell-casting | Using PICK/NOT_PICK concept, just variation of house robber I | using-picknot_pick-concept-just-variatio-ojwb | Intuition\n1. This is a good dp question of pick/not pick pattern(somewhat similar to house robber I).\n2. As we can take duplicate elements as per their freque | Hardy1 | NORMAL | 2024-06-16T06:46:01.823979+00:00 | 2024-06-16T06:46:01.824005+00:00 | 31 | false | # Intuition\n1. This is a good dp question of pick/not pick pattern(somewhat similar to house robber I).\n2. As we can take duplicate elements as per their frequency, so we can maintain a map which sorts the values of power and stores each value\'s frequency.\n# Approach\n1. Maintain a map not unordered map because we need elements in a sorted order to satisfy the constraints, in the map we have elements along with their frequency in a sorted order.\n2. Now store the values from the map into a new array and apply dynamic programming on this array.\n3. In the the solve function we take element initially as v[i]*map[v[i]].\n4. Now check the add +1, +2 to this v[i] and see if it is equal to v[i+1] or v[i+2]( as they are in a sorted order) if they are equal it means we should not take else take.\n5. Just store the maximum of take and not_take into dp.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n+m) where n=power.size() and m=number of elements in the map.\n\n- Space complexity:\nO(m) where m=number of elements in the map.\n\n# Code\n```\n\nclass Solution {\npublic:\n map<int,int> mp;\n \n long long solve(int i, vector<int> &v, vector<long long> &dp){\n if(i >= v.size()){\n return 0;\n }\n if(dp[i] != -1){\n return dp[i];\n }\n long long take = (long long)v[i] * mp[v[i]];\n long long not_take = solve(i + 1, v, dp);\n \n // Skip adjacent elements\n int next = i + 1;\n while (next < v.size() && (v[next] == v[i] + 1 || v[next] == v[i] + 2)) {\n next++;\n }\n \n return dp[i] = max(take + solve(next, v, dp), not_take);\n }\n \n long long maximumTotalDamage(vector<int>& power) {\n for(int i = 0; i < power.size(); i++){\n mp[power[i]]++; //For storing elements powers along with their frequency.\n }\n \n vector<int> v;\n for(auto it : mp){\n v.push_back(it.first); //For storing the unique elements.\n }\n \n vector<long long> dp(v.size() + 1, -1);\n return solve(0, v, dp);\n }\n};\n``` | 1 | 0 | ['Dynamic Programming', 'Ordered Map', 'C++'] | 0 |
maximum-total-damage-with-spell-casting | Easy Solution ||Beats 100% with C++|| 489ms || Hashing || Memoization || 1D DP || Optimized Solution | easy-solution-beats-100-with-c-489ms-has-0krv | Intuition\nThe code implements an algorithm to find the maximum total damage that can be dealt in a scenario where you have an array of power levels (represente | j_aryannn | NORMAL | 2024-06-16T06:24:24.579372+00:00 | 2024-06-16T06:24:24.579399+00:00 | 36 | false | # Intuition\nThe code implements an algorithm to find the maximum total damage that can be dealt in a scenario where you have an array of power levels (represented as integers) and can choose to attack enemies with these powers.\nWe can choose element by either picking it or not picking thus it requires recursion.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n- Preprocessing:\n - The code creates a frequency map (mp) to efficiently track the count of each unique power level. This avoids redundant calculations for powers with the same value.\n - A temporary vector (temp) is used to store the unique power levels for sorting.\n- Memoization with Dynamic Programming (DP):\n - The f function is a recursive helper function that uses memoization for efficiency.\n - It takes four arguments:\n - ind: The current index in the sorted array of unique power levels (temp).\n - nums: The sorted array of unique power levels (passed for clarity, not actually used within f).\n - dp: A memoization table to store previously calculated results (-1 indicates not calculated yet).\n - mp: The frequency map of power levels.\n - The base case: If ind reaches the end of the array (nums.size()), it means no more attacks can be made, so the function returns 0 (no damage dealt).\n- Recursive Calculation:\n\n - The function checks if the result for ind has already been calculated in dp. If so, it returns the stored value directly.\n - It calculates two possible scenarios and stores the maximum in dp[ind]:\n - Pick: Attack with the current power level (nums[ind]). The damage dealt is mp[nums[ind]] * nums[ind], which is the frequency of the current power level multiplied by its value. The function then recursively calls f with the next index (nInd), skipping over power levels that differ by less than or equal to 2 (as attacking with similar powers might be inefficient).\n - Not Pick: Skip attacking at the current index (ind). The function recursively calls f with the next index (ind + 1).\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n - O(n*k)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n - O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n #define ll long long\nclass Solution {\npublic:\n ll f(int ind, vector<ll>&nums, vector<ll>&dp, unordered_map<ll, ll>&mp){\n if(ind == nums.size())return 0;\n if(dp[ind] != -1)return dp[ind];\n ll pick = 0, not_pick = 0;\n \n int nInd = ind+1;\n while(nInd < nums.size() and nums[nInd] - nums[ind] <= 2)nInd++;\n pick = (1LL)*mp[nums[ind]]*nums[ind] + f(nInd, nums, dp, mp);\n not_pick = f(ind+1, nums, dp, mp);\n \n return dp[ind] = max(pick, not_pick);\n }\n long long maximumTotalDamage(vector<int>& power) {\n \n unordered_map<ll, ll>mp;\n vector<ll>temp;\n for(auto i:power){\n if(mp.find(i) == mp.end())temp.push_back(i);\n mp[i]++;\n }\n vector<ll>dp(mp.size()+1, -1);\n sort(temp.begin(), temp.end());\n return f(0, temp, dp, mp); \n }\n};\n``` | 1 | 0 | ['Hash Table', 'Recursion', 'Memoization', 'C++'] | 0 |
maximum-total-damage-with-spell-casting | Simple DP with Set and List Manipulation | simple-dp-with-set-and-list-manipulation-2n35 | Intuition\nThe intuition behind the solution is that we use all duplicates of a spell if the spell is used. Hence, we can use sets to remove duplicates. This si | rigvedmanoj | NORMAL | 2024-06-16T05:22:47.147905+00:00 | 2024-06-16T05:22:47.147935+00:00 | 30 | false | # Intuition\nThe intuition behind the solution is that we use all duplicates of a spell if the spell is used. Hence, we can use sets to remove duplicates. This simplifies the problem immensely because once duplicates are removed and the list is sorted, Only the next 3 numbers need to be checked to find a spell that is not spell+1 or spell+2.\n\n# Idea\n## Step 1: Manipulating List\nWe manipulate the list to remove duplicates and instead create a sorted 2d list that has the power and sum of duplicate powers. \n\n**Example: power = [7,1,6,6] will become power2d = [[1,1],[6,12],[7,1]]**\n\nThis is created to make the forthcoming DP better.\n\n## Step 2: DP\nThe idea behind the process is that the first element of the array cannot be added to any element before it. The second element will also include the first element if it is valid (not -1 or -2). Similarly the third element will also include the second element if it is valid. We also make sure that at every point, we are storing what the maximum value till that point should be.\n\n# Approach\n## Step 1: Manipulating List\n - Create a dictionary of all the powers. \n - Remove duplicates in power by converting to set and back to list.\n - Create 2d list containing [power,sum of same powers].\n - Sort 2d list with first value.\n \n **Example: power = [7,1,6,6] will become power2d = [[1,1],[6,12],[7,1]]**\n\n## Step 2: DP\n - Loop i from 1 to n:\n - Check if number at (i-1) index is a valid number. \n - if yes, power2d[i][1] += power2d[i-1][1]\n - else check if number at (i-2) index is a valid number.\n - if yes, power2d[i][1] += power2d[i-2][1]\n - else check if number at (i-3) index is greater than or equal to 0.\n - if yes, power2d[i][1] += power2d[i-3][1]\n - power2d[i][1] is max of power2d[i][1] and power2d[i-1][1]\n - Exit Loop\n - Return power2d[-1][1]\n\n**Valid Number implies that the index is greater than or equal to 0 and the value is not less than 1 or less than 2 of the current number**\n\n\n# Code\n```\nclass Solution: \n def maximumTotalDamage(self, power: List[int]) -> int:\n check = {}\n for val in power:\n if val in check:\n check[val] += 1\n else:\n check[val] = 1\n power = list(set(power))\n power.sort()\n power2d = []\n for p in power:\n power2d.append([p,p*check[p]])\n n = len(power2d)\n for i in range(1,n):\n val = power2d[i][0] \n if i-1 >= 0 and power2d[i-1][0] != val - 1 and power2d[i-1][0] != val - 2:\n power2d[i][1] += power2d[i-1][1] \n elif i-2 >= 0 and power2d[i-2][0] != val - 1 and power2d[i-2][0] != val - 2:\n power2d[i][1] += power2d[i-2][1] \n elif i-3 >= 0:\n power2d[i][1] += power2d[i-3][1] \n power2d[i][1] = max(power2d[i][1],power2d[i-1][1])\n return power2d[-1][1]\n``` | 1 | 0 | ['Python3'] | 0 |
maximum-total-damage-with-spell-casting | Priority Queue Unique Solution | Easy to understand | No dynamic programming | priority-queue-unique-solution-easy-to-u-9zcm | Intuition\n Describe your first thoughts on how to solve this problem. \nFor each unique number traverse in ascending order and check what last element for that | atharva1codes | NORMAL | 2024-06-16T05:15:11.831404+00:00 | 2024-06-16T05:15:11.831427+00:00 | 185 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFor each unique number traverse in ascending order and check what last element for that sequence of maximum sum can be picked and follows the constraint of last picked + 1 and last picked + 2.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nIn priority queue store -> {max sum of subsequence, current picked element for which subsequence is formed}.\n\nThe while loop inside will not run more than 2 times as need check for\nlast picked+1 and last picked + 2.Therefore this priority solution works in time complexity of O(nlogn).\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(nlogn)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```\nclass Solution {\npublic:\n long long maximumTotalDamage(vector<int>& power) {\n map<int,long long> mp;\n for(int i=0;i<power.size();i++){\n mp[power[i]]++;\n }\n long long ans=0;\n priority_queue<vector<long long>> pq;\n for(auto x:mp){\n vector<vector<long long>> temp;\n while(pq.size() && (pq.top()[1]+1==x.first || pq.top()[1]+2==x.first)){\n temp.push_back({pq.top()[0],pq.top()[1]});\n pq.pop();\n }\n if(!pq.size()){\n pq.push({x.first*x.second,x.first});\n }\n else{\n temp.push_back({pq.top()[0]+(x.first*x.second),x.first});\n }\n for(int i=0;i<temp.size();i++){\n pq.push({temp[i][0],temp[i][1]});\n }\n }\n return pq.top()[0];\n }\n};\n``` | 1 | 0 | ['Heap (Priority Queue)', 'C++'] | 1 |
maximum-total-damage-with-spell-casting | C++ easy approach using DP | c-easy-approach-using-dp-by-cookie_33-raie | 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 | cookie_33 | NORMAL | 2024-06-16T05:14:45.657720+00:00 | 2024-06-16T05:14:45.657737+00:00 | 140 | 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: O(N*LogN)\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 long long maximumTotalDamage(vector<int>& power) {\n sort(power.begin(),power.end());\n vector<vector<long long>> p;\n for(int i=0;i<power.size();i++){\n long long count=1;\n while(i+1<power.size() && power[i+1]==power[i]){\n count++;\n i++;\n }\n p.push_back({power[i],count});\n }\n vector<long long> ans(p.size());\n ans[0]=p[0][0]*p[0][1];\n for(int i=1;i<p.size();i++){\n int j=i-1;\n while(j>=0 && p[i][0]-p[j][0]<=2){\n j--;\n }\n if(j<0){\n ans[i]=max(ans[i-1],(long long)p[i][0]*p[i][1]);\n }else{\n ans[i]=max(ans[i-1],(long long)p[i][0]*p[i][1]+ans[j]);\n }\n }\n return ans[p.size()-1];\n // vector<vector<long long>> dp(p.size()+1,vector<long long>(p.size()+1,-1));\n // return helper(-1,0,p,dp);\n }\n};\n``` | 1 | 0 | ['Dynamic Programming', 'Greedy', 'C++'] | 0 |
maximum-total-damage-with-spell-casting | 🔥🔥✅ CPP || Dp Tabulation|| binary search | cpp-dp-tabulation-binary-search-by-omraj-mm4w | \n# Code\n\nclass Solution {\npublic:\n long long maximumTotalDamage(vector<int>& power) {\n unordered_map<int,long long>mp;\n for(auto it: | omrajhalwa | NORMAL | 2024-06-16T05:05:35.188183+00:00 | 2024-06-16T05:05:35.188202+00:00 | 28 | false | \n# Code\n```\nclass Solution {\npublic:\n long long maximumTotalDamage(vector<int>& power) {\n unordered_map<int,long long>mp;\n for(auto it:power) mp[it]++;\n vector<int>nums;\n for(auto it:mp){\n nums.push_back(it.first);\n }\n sort(nums.begin(),nums.end());\n \n vector<long long>dp(nums.size()+4,0);\n vector<long long>pre(nums.size()+4,0);\n \n for(int i=0;i<nums.size();i++){\n if(i>0) pre[i]=max(pre[i],pre[i-1]);\n dp[i]=pre[i];\n dp[i]+=mp[nums[i]]*1LL*nums[i];\n long long int val=nums[i]+3;\n long long int start=i+1,end=nums.size()-1;\n int indx=-1;\n while(start<=end){\n int mid=(start+end)/2;\n if(nums[mid]>=val){\n indx=mid;\n end=mid-1;\n }else{\n start=mid+1;\n }\n }\n \n if(indx!=-1){\n pre[indx]=max(dp[i],pre[indx]);\n }\n \n \n \n }\n \n long long int ans=0;\n for(auto it:dp) ans=max(ans,it);\n \n \n return ans;\n }\n};\n``` | 1 | 0 | ['Binary Search', 'Dynamic Programming', 'C++'] | 0 |
maximum-total-damage-with-spell-casting | Binary Search + Dynamic Programming O(NlogN) | binary-search-dynamic-programming-onlogn-ygxd | Intuition\n Describe your first thoughts on how to solve this problem. \nBinary Search\nUse maximum array to save the maximum possible total damage until index | Coco_007 | NORMAL | 2024-06-16T04:52:22.095389+00:00 | 2024-06-16T04:52:22.095407+00:00 | 432 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBinary Search\nUse maximum array to save the maximum possible total damage until index i. \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 maximumTotalDamage(self, power: List[int]) -> int:\n power.sort()\n dp = [0] + [p for p in power]\n maximum = [0] * (len(power) + 1)\n maximum[1] = power[0]\n for i in range(1, len(power)):\n if power[i] == power[i - 1]:\n dp[i + 1] = dp[i] + power[i]\n j = bisect.bisect_right(power, power[i] - 3)\n dp[i + 1] = max(dp[i + 1], maximum[j] + power[i])\n maximum[i + 1] = max(dp[i + 1], maximum[i])\n\n return maximum[-1]\n``` | 1 | 0 | ['Binary Search', 'Dynamic Programming', 'Python3'] | 0 |
maximum-total-damage-with-spell-casting | Easy LIS Approach Dp [cpp] | easy-lis-approach-dp-cpp-by-anish_das001-ht8w | 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 | Anish_das001 | NORMAL | 2024-06-16T04:51:14.002125+00:00 | 2024-06-16T04:51:14.002148+00:00 | 43 | 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#define ll long long\nclass Solution {\npublic:\n long long maximumTotalDamage(vector<int>& power) {\n unordered_map<int,int>mp;\n for(int i=0;i<power.size();i++){\n mp[power[i]]++;\n }\n vector<vector<long long>>nv;\n for(auto i:mp){\n ll temp=(ll)i.first * (ll)i.second;\n nv.push_back({i.first,temp});\n }\n sort(nv.begin(),nv.end());\n int n=nv.size();\n vector<long long>dp(n+1,0);\n for(int i=1;i<=n;i++){\n long long cv=nv[i-1][1];\n long long inc=cv;\n for(int j=i-2;j>=0;j--){\n if(nv[i-1][0]-nv[j][0]>2){\n inc+=dp[j+1];\n break;\n }\n }\n long long ex=dp[i-1];\n dp[i]=max(inc,ex);\n }\n return dp[n];\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
maximum-total-damage-with-spell-casting | Maximum Total Damage Calculation Using Non-Consecutive Powers | maximum-total-damage-calculation-using-n-xgy6 | Maximum Total Damage Calculation Using Non-Consecutive Powers\n\n## Intuition\nThe problem involves calculating the maximum total damage that can be achieved by | Cregan_wolf | NORMAL | 2024-06-16T04:49:39.091590+00:00 | 2024-06-16T04:49:39.091607+00:00 | 16 | false | # Maximum Total Damage Calculation Using Non-Consecutive Powers\n\n## Intuition\nThe problem involves calculating the maximum total damage that can be achieved by selecting non-consecutive power values from a given list.\n\n## Approach\n1. **Counting Damage Frequencies**:\n - Use an unordered map `damageCount` to count the frequency of each power value in the input vector `power`.\n\n2. **Sorting Unique Damages**:\n - Extract unique damage values from `damageCount` into `uniqueDamages` vector and sort them. This helps in sequential access during dynamic programming.\n\n3. **Dynamic Programming Approach**:\n - Use a dynamic programming array `dp` where `dp[i]` represents the maximum total damage achievable using non-consecutive power values up to the `i-th` index in `uniqueDamages`.\n - Initialize `dp[0]` with the product of the first unique damage value and its count (`uniqueDamages[0] * damageCount[uniqueDamages[0]]`).\n\n4. **Iterative Calculation**:\n - For each unique damage value at index `i` in `uniqueDamages`, calculate `includeCurrent` as the product of the damage value and its count.\n - Find the maximum achievable damage by either including the current damage value or excluding it based on the non-consecutive constraint.\n - Update `dp[i]` accordingly to store the maximum value.\n\n5. **Result**:\n - Return `dp[n-1]`, where `n` is the size of `uniqueDamages`, which contains the maximum total damage achievable using non-consecutive power values.\n\nThis approach ensures efficient calculation of the maximum damage using dynamic programming principles, leveraging sorting and frequency counting for optimal performance.\n\n## Complexity\n- Time complexity:\n $$ O(n \\log n) $$ due to sorting of `uniqueDamages`, where `n` is the number of unique damage values. The rest of the operations are linear with respect to the size of `uniqueDamages`.\n\n- Space complexity:\n $$ O(n) $$ for the dynamic programming array `dp` and `uniqueDamages`, where `n` is the number of unique damage values.\n\n## Code\n```cpp\n#include <vector>\n#include <unordered_map>\n#include <algorithm>\nusing namespace std;\n\nclass Solution {\npublic:\n long long maximumTotalDamage(vector<int>& power) {\n unordered_map<int, long long> damageCount;\n for (int dmg : power) {\n damageCount[dmg]++;\n }\n\n vector<int> uniqueDamages;\n for (auto& kv : damageCount) {\n uniqueDamages.push_back(kv.first);\n }\n sort(uniqueDamages.begin(), uniqueDamages.end());\n\n int n = uniqueDamages.size();\n vector<long long> dp(n, 0);\n\n for (int i = 0; i < n; ++i) {\n long long includeCurrent = uniqueDamages[i] * damageCount[uniqueDamages[i]];\n int j = i - 1;\n while (j >= 0 && uniqueDamages[j] >= uniqueDamages[i] - 2) {\n --j;\n }\n if (j >= 0) {\n includeCurrent += dp[j];\n }\n\n if (i > 0) {\n dp[i] = max(dp[i - 1], includeCurrent);\n } else {\n dp[i] = includeCurrent;\n }\n }\n\n return dp[n - 1];\n }\n};\n | 1 | 0 | ['Hash Table', 'Dynamic Programming', 'Greedy', 'Sorting', 'C++'] | 0 |
maximum-total-damage-with-spell-casting | ✅ [CPP] | 100% Beats | Recursion + Memoization + Tabulation | Very Simple + Explanation | cpp-100-beats-recursion-memoization-tabu-zbaf | Approach \n In DP problems, we generally ask the number of ways or optimal solution. In this question, we asked the optimal solution to find out the maximum tot | codemitrayt | NORMAL | 2024-06-16T04:46:15.008932+00:00 | 2024-06-16T04:48:35.913665+00:00 | 158 | false | ### Approach \n* In DP problems, we generally ask the number of ways or optimal solution. In this question, we asked the optimal solution to find out the maximum total damage.\n* We have ways to select spells. For the current spell, take or not take; if we take, then our next spell is `power[i] + 2 < power[j]`.\n* We store `jth` next valid spell for each `i`.\n\n\n\n\n\n### Recursion | Not Accepted (TLE)\n\n```\nclass Solution {\npublic:\n long long maximumTotalDamage(vector<int>& power) {\n int n = power.size();\n\n // make pair vector <element value, sum of same element>\n sort(power.begin(), power.end());\n vector<pair<int, long long>> v;\n for(int i = 0; i < n; i++) {\n if(i > 0 && power[i] == power[i - 1]) v.back().second += power[i];\n else v.push_back({power[i], power[i]});\n }\n\n // calc next valid element for i th element\n int m = v.size();\n vector<int> next(v.size(), m + 1);\n for (int i = 0; i < v.size(); i++) {\n for(int j = i + 1; j < min(i + 4, m); j++) {\n if(v[j].first >= v[i].first + 3) {\n next[i] = j;\n break;\n }\n }\n }\n \n // take/not take dp\n function<long long(int)> fn = [&](int i) -> long long {\n if(i >= m) return 0;\n return max(fn(next[i]) + v[i].second, fn(i + 1));\n };\n \n return fn(0);\n }\n};\n```\n\n### Memoization | Not accepted (TLE)\n\n```\nclass Solution {\npublic:\n long long maximumTotalDamage(vector<int>& power) {\n int n = power.size();\n\n // make pair vector <element value, sum of same element>\n sort(power.begin(), power.end());\n vector<pair<int, long long>> v;\n for(int i = 0; i < n; i++) {\n if(i > 0 && power[i] == power[i - 1]) v.back().second += power[i];\n else v.push_back({power[i], power[i]});\n }\n\n // calc next valid element for i th element\n int m = v.size();\n vector<int> next(v.size(), m + 1);\n for (int i = 0; i < v.size(); i++) {\n for(int j = i + 1; j < min(i + 4, m); j++) {\n if(v[j].first >= v[i].first + 3) {\n next[i] = j;\n break;\n }\n }\n }\n \n long long dp[m + 1];\n memset(dp, -1ll, sizeof(dp));\n function<long long(int)> fn = [&](int i) -> long long {\n if(i >= m) return 0;\n if(dp[i] != -1) return dp[i];\n return dp[i] = max(fn(next[i]) + v[i].second, fn(i + 1));\n };\n \n return fn(0);\n \n }\n};\n```\n\n### Tabulation Code | Accepted (100% Beats)\n```\nclass Solution {\npublic:\n long long maximumTotalDamage(vector<int>& power) {\n int n = power.size();\n\n // make new pair vector <same damage, sum of same damage> O(n * long(n))\n sort(power.begin(), power.end());\n vector<pair<int, long long>> v;\n for(int i = 0; i < n; i++) {\n if(i > 0 && power[i] == power[i - 1]) v.back().second += power[i];\n else v.push_back({power[i], power[i]});\n }\n\n // calc next element O(n * 4)\n int m = v.size();\n vector<int> next(v.size(), m);\n for (int i = 0; i < v.size(); i++) {\n for(int j = i + 1; j < min(i + 4, m); j++) {\n if(v[j].first >= v[i].first + 3) {\n next[i] = j;\n break;\n }\n }\n }\n \n // tabulation O(n) \n long long dp[m + 1];\n memset(dp, -1ll, sizeof(dp));\n\n dp[m - 1] = v[m - 1].second;\n dp[m] = 0;\n for(int i = m - 2; i >= 0; i--) {\n long long pick = v[i].second + dp[next[i]];\n long long notPick = dp[i + 1];\n dp[i] = max(pick, notPick);\n }\n \n return dp[0];\n }\n};\n```\n\n## Thanks, Please upvote \u2764\uFE0F | 1 | 0 | ['Dynamic Programming', 'Memoization', 'C++'] | 1 |
maximum-total-damage-with-spell-casting | Javascript sliding window dp | javascript-sliding-window-dp-by-henryche-95ss | \nconst counter = (a_or_s) => { let m = new Map(); for (const x of a_or_s) m.set(x, m.get(x) + 1 || 1); return m; };\nconst stmkey_in = (m) => new Map([...m].so | henrychen222 | NORMAL | 2024-06-16T04:40:54.647706+00:00 | 2024-06-16T04:41:18.938446+00:00 | 33 | false | ```\nconst counter = (a_or_s) => { let m = new Map(); for (const x of a_or_s) m.set(x, m.get(x) + 1 || 1); return m; };\nconst stmkey_in = (m) => new Map([...m].sort((x, y) => x[0] - y[0]));\n\nconst maximumTotalDamage = (a) => {\n let m = counter(a), n = m.size, dp = Array(n).fill(0), l = 0, max = 0;\n m = stmkey_in(m);\n let u = [...m.keys()];\n for (let i = 0; i < n; i++) {\n while (l < i && u[i] - u[l] > 2) {\n max = Math.max(max, dp[l++]);\n }\n dp[i] = max + u[i] * m.get(u[i]);\n }\n return Math.max(...dp);\n};\n``` | 1 | 0 | ['Dynamic Programming', 'Sliding Window', 'JavaScript'] | 0 |
maximum-total-damage-with-spell-casting | Maximum Total Damage Calculation | maximum-total-damage-calculation-by-creg-uqvi | Intuition\nThe problem involves calculating the maximum total damage possible from a list of power values, considering constraints on consecutive power values.\ | Cregan_wolf | NORMAL | 2024-06-16T04:34:12.184043+00:00 | 2024-06-16T04:34:12.184067+00:00 | 4 | false | # Intuition\nThe problem involves calculating the maximum total damage possible from a list of power values, considering constraints on consecutive power values.\n\n# Approach\nThe approach involves using dynamic programming (DP) to maximize the total damage. We first count occurrences of each power value using a hash map. Then, we process these unique power values in sorted order, calculating the maximum damage that can be achieved up to each power value considering the constraint that consecutive power values must differ by at least 2.\n\n# Complexity\n- Time complexity:\n The time complexity is dominated by the sorting step, which is $$ O(n \\log n) $$, where $$ n $$ is the number of unique power values. The DP iteration is linear $$ O(n) $$. Thus, the overall time complexity is $$ O(n \\log n) $$.\n\n- Space complexity:\n We use extra space for the hash map to store frequency counts $$ O(n) $$, and $$ O(n) $$ space for the DP array. Hence, the space complexity is $$ O(n) $$.\n\n# Code\n```cpp\n#include <vector>\n#include <unordered_map>\n#include <algorithm>\nusing namespace std;\n\nclass Solution {\npublic:\n long long maximumTotalDamage(vector<int>& power) {\n unordered_map<int, long long> damageCount;\n \n // Count frequencies of each power value\n for (int dmg : power) {\n damageCount[dmg]++;\n }\n\n // Extract unique power values and sort them\n vector<int> uniqueDamages;\n for (auto& kv : damageCount) {\n uniqueDamages.push_back(kv.first);\n }\n sort(uniqueDamages.begin(), uniqueDamages.end());\n\n int n = uniqueDamages.size();\n vector<long long> dp(n, 0);\n\n // Fill DP array to find maximum total damage\n for (int i = 0; i < n; ++i) {\n long long includeCurrent = uniqueDamages[i] * damageCount[uniqueDamages[i]];\n \n // Find the maximum damage that can be included without violating the constraint\n int j = i - 1;\n while (j >= 0 && uniqueDamages[j] >= uniqueDamages[i] - 2) {\n --j;\n }\n if (j >= 0) {\n includeCurrent += dp[j];\n }\n\n // Update dp[i] with the maximum damage\n if (i > 0) {\n dp[i] = max(dp[i - 1], includeCurrent);\n } else {\n dp[i] = includeCurrent;\n }\n }\n\n // Return the maximum total damage\n return dp[n - 1];\n }\n};\n | 1 | 0 | ['C++'] | 0 |
maximum-total-damage-with-spell-casting | C++ | Bottom Up DP | c-bottom-up-dp-by-prakhargupta456-u65p | Include or not include current element. Use Binary search to figure out the next possible candidate\n\nlong long maximumTotalDamage(vector<int> &power) {\n s | prakhargupta456 | NORMAL | 2024-06-16T04:32:19.988268+00:00 | 2024-06-16T04:32:19.988295+00:00 | 13 | false | Include or not include current element. Use Binary search to figure out the next possible candidate\n```\nlong long maximumTotalDamage(vector<int> &power) {\n sort(power.begin(), power.end());\n int n = power.size();\n vector<long long> dp(n + 1, 0); // Base case, dp[n]=0\n for (int i = n - 1; i >= 0; i--) {\n // Do not include curr\n // Index of next strictly greater element, do not include duplicates as well\n long long equalTarget = upper_bound(power.begin() + i, power.end(), power[i]) - power.begin();\n dp[i] = dp[equalTarget];\n\n // Include with all duplicates\n long long target = upper_bound(power.begin() + i, power.end(), power[i] + 2) - power.begin();\n dp[i] = max(dp[i], (equalTarget - i) * power[i] + dp[target]);\n }\n return dp[0];\n}\n``` | 1 | 0 | ['Dynamic Programming', 'C'] | 0 |
maximum-total-damage-with-spell-casting | SOLUTION BY ELDEN LORD HIMSELF | solution-by-elden-lord-himself-by-aditya-1vo9 | Intuition\n\n Describe your first thoughts on how to solve this problem. \nanyone can tell by the looks of it is dp the tricky part was \nto store the best p | adi_arr | NORMAL | 2024-06-16T04:21:15.692959+00:00 | 2024-06-16T04:21:15.692980+00:00 | 18 | false | # Intuition\n\n<!-- Describe your first thoughts on how to solve this problem. -->\nanyone can tell by the looks of it is dp the tricky part was \nto store the best possible rather than best possible using that element \n\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$$O(n)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n# Code\n```\nclass Solution:\n def maximumTotalDamage(self, power: List[int]) -> int:\n\n count = defaultdict(int)\n for x in power:\n count[x]+=1\n \n power = sorted(list(count.keys()))\n\n dp = [0]*len(power)\n for i in range(len(power)):\n dp[i]=0\n for j in range(1,4):\n if i-j>=0 and power[i]-power[i-j]> 2:\n dp[i]=max(dp[i],dp[i-j])\n dp[i]+= count[power[i]]*power[i]\n if i-1>=0:\n dp[i]=max(dp[i],dp[i-1])\n return dp[-1]\n \n```\n# UPVOTE THE ELDEN LORD | 1 | 0 | ['Python3'] | 0 |
maximum-total-damage-with-spell-casting | 1-D Dp Super easy soln(take/ notTake) | 1-d-dp-super-easy-solntake-nottake-by-am-29eo | Intuition\nCreate a map to store the frequency of each element so that we can directly calculate sum from the current element\n\n# Approach\nNow create a vector | am_607 | NORMAL | 2024-06-16T04:16:34.428612+00:00 | 2024-06-16T04:16:34.428643+00:00 | 29 | false | # Intuition\nCreate a map to store the frequency of each element so that we can directly calculate sum from the current element\n\n# Approach\nNow create a vector of pair of int and int to store all the values and its frequencies together because iteration in vector is faster then map \n\n# Complexity\n- Time complexity: O(N)\n<Time >\n\n- Space complexity:O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n typedef long long ll;\n \n ll dp[100003];\n \n ll f(int i,vector<pair<ll, ll>>&temp){\n int n=temp.size();\n if(i>=n)return 0;\n if(dp[i]!=-1)return dp[i];\n ll notTake= f(i+1, temp);\n \n ll take= temp[i].first* temp[i].second;\n int idx=i+1;\n for(;idx<n;idx++){\n if(temp[idx].first>temp[i].first+2)break;\n }\n take+=f(idx, temp);\n return dp[i]=max(take, notTake);\n \n }\n \n long long maximumTotalDamage(vector<int>& a) {\n sort(a.begin(), a.end());\n int n=a.size();\n memset(dp, -1, sizeof(dp));\n map<ll, ll>freq;\n for(int i=0;i<n;i++){\n freq[a[i]]++;\n }\n vector<pair<ll, ll>>temp;\n for(auto it: freq)temp.push_back(it);\n \n \n \n return f(0,temp);\n }\n};\n``` | 1 | 0 | ['C++'] | 1 |
maximum-total-damage-with-spell-casting | Beats 100% solution SimpL recursive solution C++ | beats-100-solution-simpl-recursive-solut-x5df | 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 | AshuChauhan | NORMAL | 2024-06-16T04:15:38.898021+00:00 | 2024-06-16T04:15:38.898042+00:00 | 120 | 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: recursive part: O(n ^ 2);\n sorting : O(nlogn)\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```\n#define ll long long\nclass Solution {\npublic:\n ll n;\n ll solve(vector<ll>& v, unordered_map<ll, ll>& mp, vector<ll>& dp, int i) {\n if (i < 0) return 0;\n if (dp[i] != -1) return dp[i];\n\n ll temp = v[i] * mp.at(v[i]);\n ll take = temp;\n int j = i - 1;\n while (j >= 0 && v[i] - v[j] <= 2) {\n j--;\n }\n \n take += solve(v, mp, dp, j);\n\n ll skip = solve(v, mp, dp, i - 1);\n\n dp[i] = max(take, skip);\n \n return dp[i];\n }\n \n ll maximumTotalDamage(vector<int>& power) {\n unordered_map<ll, ll> mp;\n for (auto i : power) mp[i]++;\n vector<ll> v;\n for (auto i : mp) v.push_back(i.first);\n \n sort(v.begin(),v.end());\n n = v.size();\n vector<ll> dp(n, -1); \n return solve(v, mp, dp, n - 1);\n }\n};\n``` | 1 | 0 | ['Array', 'Hash Table', 'Dynamic Programming', 'Memoization', 'C++'] | 1 |
maximum-total-damage-with-spell-casting | Python Dp + Binary Search Solution | python-dp-binary-search-solution-by-salm-xzm1 | Code\n\nclass Solution:\n def maximumTotalDamage(self, power: List[int]) -> int:\n cnt = Counter(power)\n power = list(set(power))\n pow | SalmanAd01 | NORMAL | 2024-06-16T04:14:46.814582+00:00 | 2024-06-16T04:14:46.814629+00:00 | 235 | false | # Code\n```\nclass Solution:\n def maximumTotalDamage(self, power: List[int]) -> int:\n cnt = Counter(power)\n power = list(set(power))\n power.sort()\n n = len(power)\n \n @cache\n def recur(ind):\n if ind >= n: return 0\n \n notTake = recur(ind + 1)\n take = float(\'-inf\')\n \n pos = bisect_left(power, power[ind] + 2 + 1)\n take = (cnt[power[ind]] * power[ind]) + recur(pos)\n \n return max(take, notTake)\n \n return recur(0)\n``` | 1 | 0 | ['Hash Table', 'Binary Search', 'Dynamic Programming', 'Recursion', 'Memoization', 'Sorting', 'Python', 'Python3'] | 0 |
maximum-total-damage-with-spell-casting | DP (NLOGN) + prefix indexing, tabulation DP Beats 100% | dp-nlogn-prefix-indexing-tabulation-dp-b-t0vr | \n# Code\n\nclass Solution {\npublic:\n long long maximumTotalDamage(vector<int>& v) {\n int n=v.size();\n sort(v.begin(),v.end());\n ve | himanshuyadavroxx | NORMAL | 2024-06-16T04:08:35.784795+00:00 | 2024-06-16T04:08:35.784833+00:00 | 46 | false | \n# Code\n```\nclass Solution {\npublic:\n long long maximumTotalDamage(vector<int>& v) {\n int n=v.size();\n sort(v.begin(),v.end());\n vector<int> pref(n);\n pref[0]=-1;\n for(int i=1;i<n;i++){\n if(v[i]!=v[i-1]) pref[i]=i-1;\n else pref[i]=pref[i-1];\n }\n vector<long long> dp(n);\n dp[0]=v[0];\n long long ans=v[0];\n for(int i=1;i<n;i++){\n dp[i]=v[i];\n int x=v[i]-1,y=v[i]-2;\n int idx=pref[i];\n int cnt=0;\n while(cnt<2 and idx!=-1){\n if(v[idx]!=x and v[idx]!=y){\n dp[i]=max(dp[i],dp[idx]+v[i]);\n cnt++;\n }\n idx=pref[idx];\n }\n if(v[i-1]!=x and v[i-1]!=y){\n dp[i]=max(dp[i],dp[i-1]+v[i]);\n }\n if(idx!=-1 and v[idx]!=x and v[idx]!=y) dp[i]=max(dp[idx]+v[i],dp[i]);\n ans=max(ans,dp[i]);\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['Dynamic Programming', 'C++'] | 0 |
maximum-total-damage-with-spell-casting | easy c++ beats 100% | easy-c-beats-100-by-namanbangari-fho8 | 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 | NamanBangari | NORMAL | 2024-06-16T04:07:43.147916+00:00 | 2024-06-16T04:07:43.147933+00:00 | 165 | 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 long long maximumTotalDamage(vector<int>& v) {\n ios_base::sync_with_stdio(false);cin.tie(NULL);\n sort(v.begin(),v.end());\n int n=v.size();\n vector<long long>dp(n+1,0);\n long long maxi=0;\n unordered_map<int,long long>mp;\n for(auto i:v)\n {\n mp[i]+=i;\n }\n for(int i=0;i<n;i++)\n {\n int val=v[i];\n if(i==0)\n {\n dp[i]=mp[val];\n if(maxi<dp[i])\n maxi=dp[i];\n }\n else\n {\n long long a=lower_bound(v.begin(),v.end(),v[i]-2)-v.begin();\n if(v[i]==v[i-1])\n {\n dp[i]=dp[i-1];\n continue;\n }\n if(a!=0)\n {\n a=(long long)dp[a-1];\n }\n dp[i]=a+mp[val];\n if(maxi<dp[i])\n maxi=dp[i];\n dp[i]=maxi;\n \n }\n }\n \n return maxi;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
maximum-total-damage-with-spell-casting | NlogN solution | nlogn-solution-by-kayvaibhav-x7jx | \n\n# JS Code\n\n/**\n * @param {number[]} power\n * @return {number}\n */\nvar maximumTotalDamage = function(power) {\n // Step 1: Count frequencies of each | kayvaibhav | NORMAL | 2024-06-16T04:07:10.275991+00:00 | 2024-06-16T04:07:10.276018+00:00 | 56 | false | \n\n# JS Code\n```\n/**\n * @param {number[]} power\n * @return {number}\n */\nvar maximumTotalDamage = function(power) {\n // Step 1: Count frequencies of each spell power\n let count = new Map();\n for (let ele of power) {\n if (count.has(ele)) {\n count.set(ele, count.get(ele) + 1);\n } else {\n count.set(ele, 1);\n }\n }\n\n // Step 2: Extract unique spell powers and sort them\n let arr = Array.from(count.keys()).sort((a, b) => a - b);\n let n = arr.length;\n\n // Step 3: Initialize dp array\n let dp = new Array(n + 1).fill(0);\n\n // Step 4: Dynamic Programming to compute maximum total damage\n for (let i = n - 1; i >= 0; i--) {\n let take = arr[i] * count.get(arr[i]); // Total damage if we take all spells of power arr[i]\n\n // Find the next index to skip adjacent spell powers\n let nextIndex = upperBound(arr, arr[i] + 2);\n\n // Add dp[nextIndex] if nextIndex is valid\n if (nextIndex < n) {\n take += dp[nextIndex];\n }\n\n // Update dp[i] with the maximum possible total damage\n dp[i] = Math.max(take, dp[i + 1]);\n }\n\n // Step 5: Return the maximum possible total damage\n return dp[0];\n};\n\n// Helper function to find upper bound index\nfunction upperBound(arr, target) {\n let left = 0, right = arr.length;\n while (left < right) {\n let mid = Math.floor((left + right) / 2);\n if (arr[mid] <= target) {\n left = mid + 1;\n } else {\n right = mid;\n }\n }\n return left;\n};\n``` | 1 | 0 | ['Binary Search', 'Dynamic Programming', 'Sorting', 'JavaScript'] | 0 |
maximum-total-damage-with-spell-casting | Java DP Solution | java-dp-solution-by-sudasan3-lsjl | 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 | Sudasan3 | NORMAL | 2024-06-16T04:06:42.267235+00:00 | 2024-06-16T04:06:42.267266+00:00 | 354 | 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 long maximumTotalDamage(int[] power) {\n ArrayList<long[]> mem = new ArrayList<>();\n Arrays.sort(power);\n \n int count = 0; \n for (int i = 0; i < power.length; i++) {\n if (mem.size() <= count) {\n mem.add(new long[]{power[i], 1});\n } else {\n if (mem.get(count)[0] == power[i]) {\n mem.get(count)[1]++;\n } else {\n count++;\n mem.add(new long[]{power[i], 1});\n }\n }\n }\n\n long[] dp = new long[mem.size()];\n dp[0] = mem.get(0)[0] * mem.get(0)[1];\n\n for (int i = 1; i < mem.size(); i++) {\n long currentDamage = mem.get(i)[0] * mem.get(i)[1];\n\n if (mem.get(i)[0] - mem.get(i-1)[0] > 2) {\n dp[i] = Math.max(dp[i-1], dp[i-1] + currentDamage) ;\n }else if( i >= 2 && ( mem.get(i)[0] - mem.get(i-2)[0] > 2 ))\n {\n dp[i] = Math.max(dp[i-1], dp[i-2] + currentDamage);\n } else {\n if (i >= 3) {\n dp[i] = Math.max(dp[i-1], dp[i-3] + currentDamage);\n } else {\n dp[i] = Math.max(dp[i-1], currentDamage);\n }\n }\n }\n \n return dp[mem.size()-1];\n }\n}\n``` | 1 | 0 | ['Java'] | 1 |
maximum-total-damage-with-spell-casting | ✅[DP]✅Flatten the list and DP | dpflatten-the-list-and-dp-by-nisaacdz-yus7 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nSort the powers\nFlatte | nisaacdz | NORMAL | 2024-06-16T04:04:28.244562+00:00 | 2024-06-16T04:42:24.579910+00:00 | 67 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSort the powers\nFlatten the power list\nUse 0/1 dp to find the best combination of powers\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```cpp []\nclass Solution {\npublic:\n long long maximumTotalDamage(vector<int>& power) {\n sort(power.begin(), power.end()); // Sort power vector\n\n vector<long long> vals;\n vector<int> count;\n\n for (int p : power) {\n if (vals.empty() || vals.back() != p) {\n vals.push_back(p);\n count.push_back(1);\n } else {\n count.back()++;\n }\n }\n\n vector<long long> dp(vals.size(), 0);\n\n for (int i = 0; i < dp.size(); ++i) {\n long long res = vals[i] * count[i];\n long long max_add = 0;\n\n for (int j = 1; j <= 5; ++j) {\n if (i >= j && vals[i] - vals[i - j] > 2) {\n max_add = max(max_add, dp[i - j]);\n }\n }\n\n dp[i] = res + max_add;\n }\n\n return *max_element(dp.begin(), dp.end());\n }\n};\n```\n```rust []\nimpl Solution {\n pub fn maximum_total_damage(mut power: Vec<i32>) -> i64 {\n power.sort_unstable();\n let (vals, count) = {\n let (mut vals, mut count) = (Vec::new(), Vec::new());\n for p in power {\n if vals.is_empty() || vals[vals.len() - 1] != p as i64 {\n vals.push(p as i64);\n count.push(1);\n } else {\n *count.last_mut().unwrap() += 1;\n }\n }\n (vals, count)\n };\n\n let mut dp = vec![0; vals.len()];\n \n for i in 0..dp.len() {\n let res = vals[i] * count[i];\n let mut max_add = 0;\n \n for j in 1..=5 {\n if i >= j && vals[i] - vals[i - j] > 2 {\n max_add = i64::max(max_add, dp[i - j]);\n }\n }\n\n dp[i] = res + max_add;\n }\n\n *dp.iter().max().unwrap()\n }\n}\n``` | 1 | 0 | ['Dynamic Programming', 'C++', 'Rust'] | 0 |
maximum-total-damage-with-spell-casting | Easy Solution :) | easy-solution-by-user20222-s0qs | \n\n# Code\n\nclass Solution {\npublic:\n vector< long long> memo;\n\n long long f(vector<pair<int,int>>& p, int i) {\n if (i >= p.size()) return 0 | user20222 | NORMAL | 2024-06-16T04:00:40.952761+00:00 | 2024-06-16T04:00:40.952795+00:00 | 490 | false | \n\n# Code\n```\nclass Solution {\npublic:\n vector< long long> memo;\n\n long long f(vector<pair<int,int>>& p, int i) {\n if (i >= p.size()) return 0;\n if (memo[i]!=-1) return memo[i];\n long long nt = f(p, i + 1);\n \n int nextIndex = i + 1;\n while (nextIndex < p.size() && p[nextIndex].first < p[i].first + 3) {\n ++nextIndex;\n }\n long long take = (long long)p[i].first * p[i].second + f(p, nextIndex);\n return memo[i] = max(nt, take);\n }\n\n long long maximumTotalDamage(vector<int>& power) {\n map<int, int> mp;\n for (auto& it : power) mp[it]++;\n\n vector<pair<int, int>> vp;\n for (auto& it : mp) vp.push_back(it);\n\n memo.assign(power.size(),-1);\n return f(vp, 0);\n }\n};\n``` | 1 | 0 | ['C++'] | 2 |
maximum-total-damage-with-spell-casting | DP + BinarySearch + HashMap (nlogn) | dp-binarysearch-hashmap-nlogn-by-yashmal-i39d | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | YashMalav_945 | NORMAL | 2025-04-07T20:17:41.350861+00:00 | 2025-04-07T20:17:41.350861+00:00 | 2 | false | # Intuition
<!-- 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)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
int n,m;
typedef long long int ll;
ll solve(int idx,vector<ll> &vec,map<ll,ll> &mp,vector<ll> &dp){
if(idx >= m) return 0;
if(dp[idx] != -1) return dp[idx];
ll maxD = 0;
int nxt_idx = upper_bound(vec.begin(),vec.end(),vec[idx]+2) - vec.begin();
maxD = max(maxD,mp[vec[idx]] * vec[idx] + solve(nxt_idx,vec,mp,dp));
maxD = max(maxD,solve(idx+1,vec,mp,dp));
return dp[idx] = maxD;
}
long long maximumTotalDamage(vector<int>& power) {
n = power.size();
map<ll,ll> mp;
for(int i=0;i<n;i++){
mp[power[i]]++;
}
vector<ll> vec;
for(auto &it : mp){
vec.push_back(it.first);
}
m = vec.size();
vector<ll> dp(m+1,-1);
return solve(0,vec,mp,dp);
}
};
``` | 0 | 0 | ['C++'] | 0 |
maximum-total-damage-with-spell-casting | 1D DP solution in C++ | 1d-dp-solution-in-c-by-ishikkaaa-346j | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | ishikkaaa | NORMAL | 2025-04-07T06:48:27.532750+00:00 | 2025-04-07T06:48:27.532750+00:00 | 2 | false | # Intuition
<!-- 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)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
vector<long long>dp;
long long f(vector<int>& power,int i){
if(i==power.size()) return 0;
if(dp[i]!=-1) return dp[i];
long long notTake=f(power,i+1);
long long take=power[i];
int j=i+1;
while(j<power.size() && power[j]==power[i]) {
take+=power[j];
j++;
}
while(j<power.size() && (power[i]+1==power[j] || power[i]+2==power[j])) j++;
take+=f(power,j);
if(take>notTake) return dp[i]=take;
return dp[i]=notTake;
}
long long maximumTotalDamage(vector<int>& power) {
sort(power.begin(),power.end());
if(power[0]==power[power.size()-1]){
return (long long)(power[0])*power.size();
}
dp.resize(power.size(),-1);
return f(power,0);
}
};
``` | 0 | 0 | ['C++'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.