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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
find-elements-in-a-contaminated-binary-tree | C# Suii | c-suii-by-rhazem13-v1k5 | \npublic class FindElements {\n public TreeNode myroot;\n public FindElements(TreeNode root) {\n this.myroot=root;\n root.val=0;\n tr | rhazem13 | NORMAL | 2023-10-29T11:50:42.640550+00:00 | 2023-10-29T11:50:42.640567+00:00 | 13 | false | ```\npublic class FindElements {\n public TreeNode myroot;\n public FindElements(TreeNode root) {\n this.myroot=root;\n root.val=0;\n traverse(root);\n }\n public void traverse(TreeNode root){\n if(root==null)return;\n if(root.left!=null){\n root.left.val=2*root.val+1;\n traverse(root.left);\n }\n if(root.right!=null){\n root.right.val=2*root.val+2;\n traverse(root.right);\n }\n }\n \n public bool Find(int target) {\n return searchfortarget(this.myroot,target);\n }\n public bool searchfortarget(TreeNode root, int target){\n if(root==null)return false;\n if(root.val==target)return true;\n return searchfortarget(root.left,target)||searchfortarget(root.right,target);\n }\n}\n\n/**\n * Your FindElements object will be instantiated and called as such:\n * FindElements obj = new FindElements(root);\n * bool param_1 = obj.Find(target);\n */\n``` | 2 | 0 | [] | 0 |
find-elements-in-a-contaminated-binary-tree | Easy Java Solution | easy-java-solution-by-ravikumar50-49yq | 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 | ravikumar50 | NORMAL | 2023-09-19T06:57:53.025937+00:00 | 2023-09-19T06:57:53.025961+00:00 | 244 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass FindElements {\n\n TreeNode root;\n\n static void recover(TreeNode root){\n if(root==null) return;\n\n int x = root.val;\n if(root.left!=null) root.left.val = 2*x+1;\n if(root.right!=null) root.right.val = 2*x+2;\n recover(root.left);\n recover(root.right);\n }\n\n static boolean check(TreeNode root, int a){\n if(root==null) return false;\n if(root.val==a) return true;\n\n return check(root.left,a) || check(root.right,a);\n }\n\n public FindElements(TreeNode x) {\n root = x;\n root.val = 0;\n recover(root);\n }\n \n public boolean find(int target) {\n return check(root,target);\n }\n}\n\n/**\n * Your FindElements object will be instantiated and called as such:\n * FindElements obj = new FindElements(root);\n * boolean param_1 = obj.find(target);\n */\n``` | 2 | 0 | ['Java'] | 0 |
find-elements-in-a-contaminated-binary-tree | BFS(Level Order Traversal) , C++ ✅✅ | bfslevel-order-traversal-c-by-deepak_591-wkmm | Approach\n Describe your approach to solving the problem. \nUse BFS (Level Order Traversal Format) to assign values to the nodes and store them in an unordered | Deepak_5910 | NORMAL | 2023-07-13T10:17:06.863902+00:00 | 2023-07-23T17:14:20.147101+00:00 | 152 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\nUse **BFS (Level Order Traversal Format)** to assign values to the nodes and store them in an **unordered map** to return the answer in **O(1) time** in the **find() function**.\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 FindElements {\npublic:\n unordered_map<int,bool> mp;\n FindElements(TreeNode* root) {\n queue<pair<TreeNode*,int>> q;\n q.push({root,0});\n while(!q.empty())\n {\n int n = q.size(),f = 1;\n for(int i = 0;i<n;i++)\n {\n TreeNode* node = q.front().first;\n int val = q.front().second;\n q.pop();\n if(node) mp[val] = true;\n if(node)\n {\n q.push({node->left,2*val+1});\n q.push({node->right,2*val+2});\n f = 0;\n }\n else\n {\n q.push({NULL,2*val+1});\n q.push({NULL,2*val+2});\n }\n }\n if(f) break;\n } \n }\n bool find(int t) {\n return mp[t]==true;\n }\n};\n```\n\n | 2 | 0 | ['Tree', 'Breadth-First Search', 'C++'] | 1 |
find-elements-in-a-contaminated-binary-tree | Simple DFS Solution || Beats others | simple-dfs-solution-beats-others-by-shri-ngth | \n\n# Code\n\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNod | Shristha | NORMAL | 2023-01-22T13:39:40.169024+00:00 | 2023-01-22T13:39:40.169072+00:00 | 289 | false | \n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass FindElements {\npublic:\n TreeNode* curr;\n FindElements(TreeNode* root) {\n curr=root;\n }\n bool findVal(TreeNode*root,int val,int x){\n if(!root)return false;\n if(val==0)return true;\n root->val=x;\n if(root->val==val)return true; \n return findVal(root->left,val,(2*root->val)+1)|| findVal(root->right,val,(2*root->val)+2);\n }\n \n bool find(int target) {\n return findVal(curr,target,0);\n }\n};\n\n/**\n * Your FindElements object will be instantiated and called as such:\n * FindElements* obj = new FindElements(root);\n * bool param_1 = obj->find(target);\n */\n``` | 2 | 0 | ['Depth-First Search', 'C++'] | 0 |
find-elements-in-a-contaminated-binary-tree | easy understading and memory efficient solution in js | easy-understading-and-memory-efficient-s-rnhi | ```\nvar FindElements = function(root) {\n this.tree = root\n};\n\n/ \n * @param {number} target\n * @return {boolean}\n /\nFindElements.prototype.find = fun | HabibovUlugbek | NORMAL | 2023-01-20T10:10:58.534551+00:00 | 2023-01-20T10:10:58.534602+00:00 | 160 | false | ```\nvar FindElements = function(root) {\n this.tree = root\n};\n\n/** \n * @param {number} target\n * @return {boolean}\n */\nFindElements.prototype.find = function(target) {\n this.tree.val = 0;\n function find(target,root){\n if(!root) return false;\n let val = root.val\n if(val === target) return true;\n if(root.left) {\n root.left.val = 2*val +1;\n if(find(target,root.left)) return true\n }\n if(root.right) {\n root.right.val = 2*val +2;\n if(find(target,root.right))return true\n }\n return false\n }\n return find(target,this.tree)\n \n}; | 2 | 0 | ['Tree', 'JavaScript'] | 0 |
find-elements-in-a-contaminated-binary-tree | C++ || Array and Tree ✅ || Easiest Approach 🔥 | c-array-and-tree-easiest-approach-by-ujj-qeyh | \n# Approach\nForming a array to store binary tree. The values that is asked to store is similar to index that we use to store element of tree in array. Only st | UjjwalAgrawal | NORMAL | 2023-01-04T16:01:03.764863+00:00 | 2023-01-04T16:02:01.304240+00:00 | 370 | false | \n# Approach\nForming a array to store binary tree. The values that is asked to store is similar to index that we use to store element of tree in array. Only storing a tree will take O(n). Otherwise find function will take O(1) time as it is only checking whether at target value, i.e., same as index of array is -1 or not.\n\n# Complexity\n- Time complexity: $$O(n)$$ ---- where n is the number of nodes in tree.\n\n# Code\n```\nclass FindElements {\n vector<int> treeArr;\npublic:\n FindElements(TreeNode* root) {\n treeArr = vector<int>(1e6+1, -1);\n dfs(root, 0);\n }\n\n void dfs(TreeNode* root, int i){\n if(root == NULL || i > 1e6)\n return;\n\n treeArr[i] = i;\n dfs(root->left, 2*i+1);\n dfs(root->right, 2*i+2);\n }\n \n bool find(int target) {\n if(treeArr[target] == -1)\n return false;\n\n return true;\n }\n};\n```\n\n---\n\n```\nIf you learn/found something new please upvote \uD83D\uDC4D\n```\n | 2 | 0 | ['Tree', 'Depth-First Search', 'C++'] | 0 |
find-elements-in-a-contaminated-binary-tree | Java Easy Solution using HashSet | java-easy-solution-using-hashset-by-avad-afuo | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nSave all the nodes value in HashSet\n Describe your approach to solving t | avadarshverma737 | NORMAL | 2022-11-15T05:47:21.294297+00:00 | 2022-11-15T05:47:21.294342+00:00 | 340 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nSave all the nodes value in HashSet\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 FindElements {\n\n Set<Integer> nodes;\n public FindElements(TreeNode root) {\n nodes = new HashSet<>();\n recover(root,0);\n }\n private void recover(TreeNode root, int parent){\n if(root == null){\n return;\n }\n root.val = parent;\n nodes.add(root.val);\n recover(root.left,2*parent+1);\n recover(root.right,2*parent+2);\n }\n public boolean find(int target) {\n return nodes.contains(target);\n }\n}\n``` | 2 | 0 | ['Hash Table', 'Java'] | 0 |
find-elements-in-a-contaminated-binary-tree | Go with map | go-with-map-by-tuanbieber-k26b | \ntype FindElements struct {\n m map[int]struct{}\n}\n\nfunc Constructor(root *TreeNode) FindElements {\n m := make(map[int]struct{})\n \n var recov | tuanbieber | NORMAL | 2022-07-16T15:14:06.122235+00:00 | 2022-07-16T15:14:06.122267+00:00 | 106 | false | ```\ntype FindElements struct {\n m map[int]struct{}\n}\n\nfunc Constructor(root *TreeNode) FindElements {\n m := make(map[int]struct{})\n \n var recoverTree func(*TreeNode, int)\n recoverTree = func(root *TreeNode, val int) {\n if root == nil {\n return\n }\n \n m[val] = struct{}{}\n \n recoverTree(root.Left, 2*val+1)\n recoverTree(root.Right, 2*val+2)\n }\n \n recoverTree(root, 0)\n \n return FindElements {\n m: m,\n }\n}\n\n\nfunc (this *FindElements) Find(target int) bool {\n if _, ok := this.m[target]; ok {\n return true\n }\n \n return false\n}\n\n``` | 2 | 0 | ['Recursion', 'Go'] | 0 |
find-elements-in-a-contaminated-binary-tree | C++: Easy and Concise | c-easy-and-concise-by-abhijeet_26-0u68 | \nclass FindElements {\nprivate:\n unordered_set<int>st;\n void makeTree(TreeNode* root,int data)\n {\n if(!root) return;\n root->val=dat | abhijeet_26 | NORMAL | 2022-01-19T14:34:35.447076+00:00 | 2022-01-19T14:34:35.447114+00:00 | 162 | false | ```\nclass FindElements {\nprivate:\n unordered_set<int>st;\n void makeTree(TreeNode* root,int data)\n {\n if(!root) return;\n root->val=data;\n st.insert(data);\n makeTree(root->left,(data*2+1));\n makeTree(root->right,(data*2+2));\n \n }\n \npublic:\n FindElements(TreeNode* root) {\n makeTree(root,0);\n }\n \n bool find(int target) {\n return st.find(target)!=st.end();\n }\n};\n\n``` | 2 | 0 | ['Recursion', 'C', 'Ordered Set', 'C++'] | 0 |
find-elements-in-a-contaminated-binary-tree | C++ Easy To Implementation | c-easy-to-implementation-by-beast_vin-r2uy | class FindElements {\npublic:\n\n sets;\n void solve(TreeNode root)\n {\n if(root)\n {\n int x=root->val;\n i | beast_vin | NORMAL | 2021-12-14T11:08:37.619762+00:00 | 2021-12-14T11:08:37.619804+00:00 | 103 | false | class FindElements {\npublic:\n\n set<int>s;\n void solve(TreeNode *root)\n {\n if(root)\n {\n int x=root->val;\n if(root->left)\n {\n root->left->val=2*x+1;\n s.insert(2*x+1);\n solve(root->left);\n }\n if(root->right)\n {\n root->right->val=2*x+2;\n s.insert(2*x+2);\n solve(root->right);\n }\n }\n }\n FindElements(TreeNode* root) {\n root->val=0;\n s.insert(0);\n solve(root);\n } \n \n bool find(int t) {\n if(s.find(t)!=s.end())\n return true;\n return false;\n }\n}; | 2 | 0 | ['Depth-First Search', 'Recursion', 'C', 'Ordered Set'] | 0 |
find-elements-in-a-contaminated-binary-tree | C++ || EASY MAP | c-easy-map-by-the_expandable-b7vm | ```\n/\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() : val(0), | the_expandable | NORMAL | 2021-12-13T09:09:49.967086+00:00 | 2021-12-13T09:09:49.967113+00:00 | 62 | false | ```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass FindElements {\npublic:\n int x = 0 ; \n map<int,int>mp ; \n void build(TreeNode *root , int x)\n {\n if(root == nullptr)\n {\n return ; \n }\n root->val = x ; \n mp[x]++ ; \n build(root->left,2*x+1);\n build(root->right,2*x+2);\n }\n FindElements(TreeNode* root) {\n build(root,0);\n }\n \n bool find(int target) {\n if(mp.find(target) != mp.end())\n return true;\n return false;\n }\n};\n\n/**\n * Your FindElements object will be instantiated and called as such:\n * FindElements* obj = new FindElements(root);\n * bool param_1 = obj->find(target);\n */ | 2 | 0 | [] | 0 |
find-elements-in-a-contaminated-binary-tree | C++ || 99% faster || Simple DFS | c-99-faster-simple-dfs-by-_blackdev-1x9i | ```\nclass FindElements {\npublic:\n vector mapper;\n FindElements(TreeNode root) {\n mapper.resize(1000005,false);\n filterThis(root,0);\n | _BlackDev | NORMAL | 2021-07-26T10:27:26.869612+00:00 | 2021-07-26T10:27:26.869654+00:00 | 96 | false | ```\nclass FindElements {\npublic:\n vector<bool> mapper;\n FindElements(TreeNode* root) {\n mapper.resize(1000005,false);\n filterThis(root,0);\n }\n void filterThis(TreeNode* root, int x) {\n if(!root) return;\n if(x<=1000001) {\n mapper[x] = true; \n filterThis(root->left, 2*x+1);\n filterThis(root->right,2*x+2);\n }\n }\n bool find(int target) {\n return mapper[target];\n }\n}; | 2 | 0 | [] | 1 |
find-elements-in-a-contaminated-binary-tree | O(1) find Operation Approach 🔥 | o1-find-operation-approach-by-faisalalik-u1hu | \tclass FindElements {\n\tpublic:\n bool arr[2097152]={false}; // it is stated that max height of tree is less than 20,\n\t//so max nodes will be 2^height+1\ | faisalalik9 | NORMAL | 2021-06-30T12:20:49.650048+00:00 | 2021-06-30T12:20:49.650080+00:00 | 86 | false | \tclass FindElements {\n\tpublic:\n bool arr[2097152]={false}; // it is stated that max height of tree is less than 20,\n\t//so max nodes will be 2^height+1\n\t\n FindElements(TreeNode* root) {\n cure(root,0);\n }\n void cure(TreeNode* root,int i){\n if(root==NULL)\n return;\n \n root->val = i;\n arr[i] = true;\n cure(root->left,2*i+1);\n cure(root->right,2*i+2);\n \n }\n \n bool find(int target) {\n return arr[target]; // O(1) time complexity\n\t\t}\n\t}; | 2 | 2 | [] | 0 |
find-elements-in-a-contaminated-binary-tree | [C++] No HashMap, Bit Path | c-no-hashmap-bit-path-by-ieasons-vy9o | idea: Use a stack to store the bit path and then reversely find.\n\nclass FindElements {\npublic:\n FindElements(TreeNode* root) {\n r = root;\n | ieasons | NORMAL | 2020-01-21T03:51:13.895139+00:00 | 2020-01-21T03:51:13.895172+00:00 | 284 | false | idea: Use a stack to store the bit path and then reversely find.\n```\nclass FindElements {\npublic:\n FindElements(TreeNode* root) {\n r = root;\n if (!root) return;\n build(root, 0);\n }\n \n bool find(int target) {\n stack<bool> st;\n int t = target;\n while (t > 0) {\n if (t % 2) {\n st.push(true);\n t = (t - 1) / 2;\n } else {\n st.push(false);\n t = t / 2 - 1;\n }\n }\n TreeNode *cur = r;\n while (!st.empty()) {\n if (!cur) return false;\n if (st.top()) {\n cur = cur->left;\n } else {\n cur = cur->right;\n }\n st.pop();\n }\n if (cur && cur->val == target) return true;\n return false;\n }\n \nprivate:\n TreeNode *r;\n \n void build(TreeNode* root, int val) {\n root->val = val;\n int n = 2 * val + 1;\n if (root->left) build(root->left, n);\n if (root->right) build(root->right, n + 1);\n }\n};\n``` | 2 | 1 | [] | 0 |
minimum-initial-energy-to-finish-tasks | [Python] clean greedy solution with explanation | python-clean-greedy-solution-with-explan-ktk7 | Idea\n\nFor task = [cost, mmin], it needs mmin energy to start but only needs cost energy to finish. Let\'s define mmin - cost as the energy saved for this task | alanlzl | NORMAL | 2020-11-22T04:00:57.785106+00:00 | 2020-11-22T04:11:25.707079+00:00 | 6,171 | false | **Idea**\n\nFor `task = [cost, mmin]`, it needs `mmin` energy to start but only needs `cost` energy to finish. Let\'s define `mmin - cost` as the energy `saved` for this task.\n\nTo start a new task, we need to add `mmin - prev_saved` energy. Therefore, we want to complete the tasks with higher `saved` first so as to maximize `prev_saved`. This leads to a greedy solution.\n\nThe order doesn\'t matter for tasks with the same `saved`. These tasks just need `saved + sum(cost)` energy altogether.\n\n\n</br>\n\n**Complexity**\n\n- Time complexity: `O(NlogN)`\n- Space complexity: `O(1)`\n\n</br>\n\n**Python**\n\n```\nclass Solution:\n def minimumEffort(self, tasks: List[List[int]]) -> int:\n tasks.sort(key=lambda x: x[0] - x[1])\n ans = cur = 0\n for cost, mmin in tasks:\n if mmin > cur:\n ans += (mmin - cur)\n cur = mmin\n cur -= cost\n return ans\n```\n | 125 | 3 | [] | 20 |
minimum-initial-energy-to-finish-tasks | [Java/C++/Python] Sort, and some story | javacpython-sort-and-some-story-by-lee21-0hjg | Intuition\nNeed to sort by minimum - actual\n\n\n# Explanation\nWe have n investor,\neach investor can invest actual energy,\nand he think your company have min | lee215 | NORMAL | 2020-11-22T04:05:01.023040+00:00 | 2020-11-29T09:43:40.512534+00:00 | 8,163 | false | # Intuition\nNeed to sort by `minimum - actual`\n<br>\n\n# Explanation\nWe have `n` investor,\neach investor can invest `actual` energy,\nand he think your company have `minimum` value.\n\nIf you already have at least `minimum - actual` energy,\nthe investory will invest you `actual` energy.\n\nAssuming you get all investment,\nhow many energy you have at least in the end?\n\nWe sort by the energy required `minimum - actual`.\n`res` is our current energy.\nEach round we will get energy `a` and reach `max(res + a, m)`.\nReturn directly `res` in the end.\n<br>\n\n# Continue the story\nThe following explanation is from @kaiwensun, vote for him.\n\n`minimum - actual` is the "bar" of an investor.\nif your company doesn\'t already have at least `minimum - actual` energy/value\nwhen the investor is assessing your company,\nyou don\'t meet the investor\'s bar.\nThey don\'t want to invest to you.\n\nBut don\'t worry, you can pay some extra energy/money\nfrom your own pocket to reach `minimum - actual` and meet the bar,\nthen the investor will invest actual energy.\n\nEventually, every investor will invest actual to you.\nYou want to pay as little out-of-pocket energy/money as possible.\n\nSo you want your company\'s energy/value to be as high as possible\nbefore visiting an investor to let it asses your company.\n\nIn other words, you want to first visit those investors whose bar is lower.\n\nSo we sort by investors by their "bar",\ni.e. by their `minimum - actual`.\n<br>\n\n# Complexity\nTime `O(sort)`\nSpace `O(sort)`\n<br>\n\n**Java**\n```java\n public int minimumEffort(int[][] A) {\n int res = 0;\n Arrays.sort(A, (a1, a2) -> (a1[1] - a1[0]) - (a2[1] - a2[0]));\n for (int[] a : A) {\n res = Math.max(res + a[0], a[1]);\n }\n return res;\n }\n```\n**C++**\n```cpp\n int minimumEffort(vector<vector<int>>& A) {\n int res = 0;\n for (auto &a : A)\n a[0] = a[1] - a[0];\n sort(A.begin(), A.end());\n for (auto &a : A)\n res = max(res + a[1] - a[0], a[1]);\n return res;\n }\n```\n**Python:**\n```py\n def minimumEffort(self, A):\n A.sort(key=lambda a: a[1] - a[0])\n res = 0\n for a, m in A:\n res = max(res + a, m)\n return res\n```\n | 119 | 6 | [] | 17 |
minimum-initial-energy-to-finish-tasks | // Easy Code with Comments - Sort and Borrow energy when necessary | easy-code-with-comments-sort-and-borrow-odcx9 | \n// Easy Code with Comments - Sort and Borrow energy when necessary\n\n\n// a[1] & b[1] are minimum energies while\n// a[0] & b[0] are actual energies required | interviewrecipes | NORMAL | 2020-11-22T04:01:44.655886+00:00 | 2020-11-22T04:03:11.351444+00:00 | 2,695 | false | ```\n// Easy Code with Comments - Sort and Borrow energy when necessary\n\n\n// a[1] & b[1] are minimum energies while\n// a[0] & b[0] are actual energies required.\n// Sort the array in the descending order of (minimum - actual).\n// (minimum - actual) is the amount of energy that remains after \n// finishing a task. So we should try to accumulate as much energy\n// as possible in the beginning to complete the tasks coming up\n// ahead. Hence, sort the array in descending order based on the \n// amount of energy that will be remaining.\nbool comparator(vector<int> &a, vector<int>&b) {\n return ((a[1]-a[0] > b[1]-b[0]));\n}\n// Example: [[1, 10], [1, 5], [1,20]] --> [[1, 20], [1, 10], [1, 5]]\n\n\nclass Solution {\npublic:\n int minimumEffort(vector<vector<int>>& tasks) {\n int answer = 0;\n int n = tasks.size();\n sort(tasks.begin(), tasks.end(), comparator); // custom sort, see the comment above.\n int energy = 0; // assume initial energy is 0 and we will borrow whenever necessary.\n for (int i=0; i<n; i++) {\n if (energy < tasks[i][1]) { // if sufficient energy is not available,\n int borrow = tasks[i][1]-energy; // borrow some energy.\n answer += borrow;\n energy += borrow; // energy increased because of borrowing.\n }\n energy = energy - tasks[i][0]; // now spend the energy for the task.\n }\n return answer; // total borrowed energy.\n }\n};\n``` | 97 | 0 | [] | 10 |
minimum-initial-energy-to-finish-tasks | A real strategy to invest | a-real-strategy-to-invest-by-chipbk10-g0mi | If you want to invest on a project [x,y], you must have y money. Once finished, you gain y-x money. So, which project you should invest first to build up a good | chipbk10 | NORMAL | 2020-11-23T13:38:09.490761+00:00 | 2020-11-24T11:06:54.873477+00:00 | 1,375 | false | If you want to invest on a project `[x,y]`, you must have `y` money. Once finished, you gain `y-x` money. So, which project you should invest first to build up a good capital for the next investments?\n\nMy advice is to invest on projects which are able to bring back the highest profitability `y-x`. Even, in the case `y` is very big, don\'t be afraid, you can loan extra money from other sources (banks, family, friends) to have enough `y` money. The secret is you know that at this moment, `y-x` is the most profitable.\n\nSo, we can arrange the projects by decreasing profits, and borrow money to invest if our capital is not enough.\n\n```\n\t\tint res = 0, cur = 0;\n Arrays.sort(A, (a, b) -> (b[1] - b[0]) - (a[1] - a[0]));\n \n for (int[] a : A) {\n if (cur < a[1]) { // current capital not enought to invest?\n res += a[1]-cur; // borrow\n cur = a[1];\n }\n cur -= a[0]; // gained profit\n }\n return res;\n```\n\nNow, we can apply this strategy in real life. Tell me on what we should invest now? `gold`, `stock`, `bitcoin`, etc... | 43 | 1 | [] | 3 |
minimum-initial-energy-to-finish-tasks | Explanation on why sort by difference | explanation-on-why-sort-by-difference-by-g98d | Intuition\n\nSort by the difference mininum - actual and then process one by one.\n\nHow to come up with intuition\n\nObserve the examples.\nThe most important | mengmamax | NORMAL | 2020-11-22T04:41:15.794364+00:00 | 2020-11-22T10:49:39.526483+00:00 | 1,961 | false | **Intuition**\n\nSort by the difference `mininum - actual` and then process one by one.\n\n**How to come up with intuition**\n\nObserve the examples.\nThe most important thing after receiving a problem is to understand it.\nHere understand means not only reading the text, but also going through the examples.\nOne can find the pattern by observing 3 examples that the minimum energy is achieved\nin an order of increasing difference.\n\n**Proof of why sort by difference**\n\n*Quick observation*: order matters. Just read example 1 again if you\'re not sure.\n\nSuppose we are given two tasks, `[a, a + c1]` and `[b, b + c2]`, where `c1 < c2` and `a, b` are two arbitrary numbers. We have two possible ordering:\nOrder 1: `[a, a + c1], [b, b + c2]`\nOrder 2: `[b, b + c2], [a, a + c1]`\n\nOrder 1 gives a result `[a + b, max(a + b + c1, b + c2)]`, and order 2 `[a + b, max(a + b + c2, a + c1)]`.\nLet `m1 = max(a + b+ c1, b + c2)`, `m2 = max(a + b + c2, a + c1)`. Since the final result depends \non `min(m1, m2)`, we should arrange in an order that results in a smaller minimum.\n\nWe want to prove that `[a, a + c1]` should always come first.\n1. Obviously, `a + b + c2 > a + c1` since `c2 > c1`.\n2. If `a + b + c1 >= b + c2`, i.e., `c1 < c2 <= c1 + a`, then we know `m1 = a + b + c1 <= a + b + c2 = m2`. So `[a, a + c1]` should come first.\n3. If `a + b + c1 < b + c2`, i.e., `c2 > a + c1 > c1`, then `m1 = b + c2 < a + b + c2 = m2`. Again, `[a, a + c1]` should come first.\n\nThis completes the proof for the case `c1 < c2`. The case `c1 > c2` can be proved similarly. The case `c1 == c2` is trivial.\n\nSo, in all cases, `[a, a + c1]` should always come first.\n\n**Algorithm processing order vs actual task finish order**\n\nWe solve the problem in increasing difference order, while the actual tasks are finished in decreasing order. That\'s why we process in order `[a, a+c1], [b, b+c2]` but actually `[b, b+c2]` is finished first.\n\nIn other words, for a list of tasks `t1, t2, t3, ... tn`, we process in this order to get our solution, the minimum energy. But this minimum is achieved by finishing tasks in order `tn, ..., t2, t1`.\n\n**Code sample**\n```python\nclass Solution:\n def minimumEffort(self, tasks: List[List[int]]) -> int:\n tasks.sort(key=lambda t: t[1] - t[0])\n res = [0, 0]\n for t0, t1 in tasks:\n res = [res[0] + t0, max(res[1]+t0, t1)]\n return max(res)\n``` | 28 | 2 | [] | 7 |
minimum-initial-energy-to-finish-tasks | [Java] - BST pattern - same Leetcode problems and Greedy Idea - 100% | java-bst-pattern-same-leetcode-problems-v71f5 | Idea 1: BST \n\nHow can we break this issue into a smaller problem? \nThink about this :\n\n What is the minimum potential result can it be ? --> min = sum of a | tea_93 | NORMAL | 2020-11-22T04:08:23.679950+00:00 | 2020-11-25T05:04:41.933572+00:00 | 1,396 | false | **Idea 1: BST **\n\nHow can we break this issue into a smaller problem? \nThink about this :\n\n* What is the minimum potential result can it be ? --> min = sum of all task[0]\n* What is the maximum potential result can it be ? --> max = sum of all ( task[0] + task[1] )\n\n If result is a number (X). is X a valid number/result ?\n* \t\t if yes -> can we reduce the number X to make it mininum and still valid ?\n* \t\t if no -> we need to increase X to make it valid. \n\nThe only small difference compare to other same problems is building the MaxHeap - The biggest task[1] - task[0] will need to be consider first \n\n\n\n\n* Same problems : \n\n\n875\t- Koko Eating Bananas \n410\t- Split Array Largest Sum \n1231 - Divide Chocolate\n134 - Gas Station \n\nHere is a great resource (thanks @aravind_dev): \nhttps://leetcode.com/discuss/general-discussion/691825/Binary-Search-for-Beginners-Problems-or-Patterns-or-Sample-solutions\n\n```\nclass Solution {\n public int minimumEffort(int[][] tasks) {\n PriorityQueue<int[]> maxHeap = new PriorityQueue<>((a, b) -> (b[1] - b[0]) - (a[1] - a[0]));\n \n long min = 0;\n long max = 0;\n \n for (int[] t : tasks) {\n maxHeap.add(t);\n min += t[0]; // the result can not be smaller than min\n max += t[1]; // the result can not be greater than max\n }\n\t\t\n\t\t// BST - Binary search tree\n while (min < max) {\n long mid = (max + min) / 2;\n PriorityQueue<int[]> new_pq = new PriorityQueue(maxHeap);\n \n if (isValid(new_pq, mid)) {\n max = mid;\n } else {\n min = mid + 1;\n }\n } \n \n return (int)min;\n }\n \n public boolean isValid(PriorityQueue<int[]> maxHeap, long mid) {\n while (!maxHeap.isEmpty()) {\n int[] top = maxHeap.poll(); \n \n if (mid < top[1])\n return false;\n mid -= top[0];\n }\n return true;\n }\n}\n```\n\n\n\n**Idea 2 : Greedy **\n \nSort by diff (task[1] - task[0])\n\nWhy sort that way ?\n - Because we need to save the most energy for the next one\n\n\nLook at 2 examples: \n1. example 1: [1-3] and [5-10]; which one you want to solve first? \n1. example 2: [1-6] and [9-10]; now which one? \n\n\n```\nclass Solution {\n public int minimumEffort(int[][] tasks) {\n Arrays.sort(tasks, (a, b) -> (b[1] - b[0]) - (a[1] - a[0]));\n \n int res = 0, energy = 0;\n \n for (int[] task : tasks) {\n if (energy < task[1]) { // if we do not have enough energy for the next one\n res += task[1] - energy;\n energy = task[1];\n }\n \n energy -= task[0];\n }\n return res;\n }\n}\n``` | 20 | 0 | [] | 5 |
minimum-initial-energy-to-finish-tasks | C++ Sort by [Minimum - Actual] | c-sort-by-minimum-actual-by-votrubac-4a5s | The idea is to first do tasks with the largest difference between required and consumed energy.\n \nThus, we sort the tasks, and then just track the energy r | votrubac | NORMAL | 2020-11-22T04:13:47.607965+00:00 | 2020-11-22T04:13:47.608007+00:00 | 1,724 | false | The idea is to first do tasks with the largest difference between required and consumed energy.\n \nThus, we sort the tasks, and then just track the energy requried.\n\n```cpp\nint minimumEffort(vector<vector<int>>& tasks) {\n int energy = 0, res = 0;\n sort(begin(tasks), end(tasks), [](vector<int> &t1, vector<int> &t2) \n { return t1[1] - t1[0] > t2[1] - t2[0]; });\n for (auto &t : tasks) {\n res += max(0, t[1] - energy);\n energy = max(energy, t[1]) - t[0];\n }\n return res;\n}\n``` | 19 | 3 | [] | 5 |
minimum-initial-energy-to-finish-tasks | [Python] Greedy solution with intuition and proof | python-greedy-solution-with-intuition-an-5u2f | The code to the greedy approach is relatively straightforward. However what makes it hard is actually proving that the greedy approach is correct.\n\nIntuition: | algomelon | NORMAL | 2020-11-24T00:36:43.237079+00:00 | 2020-11-24T18:40:51.019488+00:00 | 595 | false | The code to the greedy approach is relatively straightforward. However what makes it hard is actually proving that the greedy approach is correct.\n\nIntuition:\nEach time we process a task, we\'ll have some energy left over that we can carry forward onto the next task. Ideally we\'d then want to carry as much as possible so on the next task, as little as possible energy is required.\n\nProof:\nWe have our greedy solution `G` that orders tasks in descending order of `minimum`<sub>i</sub>- `actual`<sub>i</sub>. That is for all `i`, `minimum`<sub>i</sub>- `actual`<sub>i</sub> >= `minimum`<sub>i+1</sub>- `actual`<sub>i+1</sub>. Let\'s say someone comes along with some competing solution `M` *different* from `G`. There then must exist a pair of "inversions", [`minimum`<sub>i</sub>, `actual`<sub>i</sub>] and [`minimum`<sub>i+1</sub>, `actual`<sub>i+1</sub>] such that `minimum`<sub>i</sub>- `actual`<sub>i</sub> <= `minimum`<sub>i+1</sub>- `actual`<sub>i+1</sub>. (If there are no such inversions, then `G` is the same as `M` and there\'s nothing to prove)\n\nTo save some typing, let\'s call the inverted pair of tasks in the order `[x, x + d0]` , `[y, y + d1]` found in `M` whereas we have the opposite, greedy, order `[y, y + d1]`, `[x, x + d0]` found in in `G`. Here `d1 >= d0`, the reason for the inversion.\n\nTo process `[x, x + d0]` , `[y, y + d1]` in `M`, we\'ll need some amount of energy, let\'s call it `E`<sub>m</sub>. It must be true that: `E`<sub>m</sub> `>= x + d0` *and* `E`<sub>m</sub> `- x >= y + d1`. Why? Because we\'ll need at least `x + d0` to begin processing the first task and after having processed the task, we would have spent `x` amount of energy and would now require an additional `y + d1` amount to begin processing the second task. It then follows that `E`<sub>m</sub> `>= x + d0` *and* `E`<sub>m</sub>` >= x + y + d1` which means `E`<sub>m</sub> `>= max(x + d0, x + y + d1)`. But since `d1 >= d0`, `x + y + d1 >= x + d0` so actually `E`<sub>m</sub>`= x + y + d1`.\n\nSimilarly to process `[y, y + d1]`, `[x, x + d0]` , in `G`, we\'ll need the amount of energy we\'ll call `E`<sub>g</sub>. By the same logic, we have `E`<sub>g</sub> `>= max(y + d1, x + y + d0)`. We can\'t reduce this further like we did with `E`<sub>m</sub>.\n\nWhew! Okay almost there! We now want to show that in all cases, `E`<sub>m</sub>` >= E`<sub>g</sub>. That is `M` is not as energy-efficient as `G` at this point.\nCase 1: if `y + d1 >= x + y + d0`, then `E`<sub>g</sub> `= y + d1`. But notice `E`<sub>m</sub>`= x + y + d1` so `E`<sub>m</sub> >= `E`<sub>g</sub>.\nCase 2: If ` x + y + d0 >= y + d1`, then `E`<sub>g</sub> `= x + y + d0`. Since `d1 >= d0`, we have `x + y + d1 >= x + y + d0`. But that\'s just `E`<sub>m</sub> >= `E`<sub>g</sub>.\nSo we\'ve now shown given any solution `M` different from `G`, wherever we find some inversion where its task ordering differs from that in `G`, the energy required at that point will be higher than that in `G`. It then follows we can simply correct each such inversion in `M` to get a smaller required energy and when all inversions are fixed, it will converge to the greedy, optimal solution.\n\n\n```\nclass Solution:\n def minimumEffort(self, tasks: List[List[int]]) -> int:\n # We want to go through tasks in descending order of energy we could carry\n # over to the next task\n tasks.sort(key=lambda x:-(x[1] - x[0]))\n \n curr_energy = 0\n borrowed = 0\n for i in range(len(tasks)):\n need = max(0, max(tasks[i]) - curr_energy)\n borrowed += need\n curr_energy = curr_energy + need - tasks[i][0]\n\n return borrowed | 16 | 0 | [] | 2 |
minimum-initial-energy-to-finish-tasks | C++ | easy solution using sorting | c-easy-solution-using-sorting-by-sekhar1-r4cv | https://www.youtube.com/watch?v=CgaYzm3s1SU\n\nThe minimum energy required will be >= total energy of all tasks + some additional energy required for the tasks | sekhar179 | NORMAL | 2020-11-28T17:01:19.287095+00:00 | 2020-11-29T12:15:32.484552+00:00 | 612 | false | https://www.youtube.com/watch?v=CgaYzm3s1SU\n\nThe minimum energy required will be >= total energy of all tasks + some additional energy required for the tasks having "minimum energy" requirement >= actual energy requirement.\nso "total enery of all tasks" <= answer <= "total minimum energy of all tasks"\nKey points:\n1. To minimize the answer we need to process the tasks which have more gap between their actual and minimum energy requirement.\n2. Sort all these tasks accoring to the above ordering\n3. Calculate total energy of all tasks and start processing with this energy\n4. Add additional energy to answer wherever the minimum requirement is not satisfied using current total energy\n```\nclass Solution {\npublic:\n static bool mysort(vector<int> &a, vector<int> &b) {\n return (a[1] - a[0]) > (b[1] - b[0]);\n }\n int minimumEffort(vector<vector<int>>& tasks) {\n sort(tasks.begin(), tasks.end(), mysort);\n int total = 0;\n for (auto task: tasks)\n total += task[0];\n int res = total;\n for (auto task: tasks) {\n if (task[1] > total) // If the tasks minimum requirement is more than current total energy\n total += task[1] - total; // Add the additional energy required to the total \n total -= task[0];\n }\n return res + total;\n }\n};\n``` | 8 | 0 | ['C'] | 2 |
minimum-initial-energy-to-finish-tasks | C++ Understandable Solution | c-understandable-solution-by-sairakesh-uh1f | Just add the total actual energy\'s required to get all done, and the minimum difference between the actual and minimum energy required to kick start the proces | sairakesh | NORMAL | 2020-11-22T04:19:55.867014+00:00 | 2020-11-23T10:15:52.937423+00:00 | 722 | false | * Just add the total actual energy\'s required to get all done, and the minimum difference between the actual and minimum energy required to kick start the process.\n* Another case is where the minimum energy required could be very high, thus we find the maximum of the required energies.\n* Now we return the maximum of the difference values and the max of required energy.\n```\nclass Solution {\npublic:\n int minimumEffort(vector<vector<int>>& tasks) {\n int diff=INT_MAX,ans=0;\n for(auto i : tasks){\n diff=min(diff,i[1]-i[0]);\n ans+=i[0];\n }\n int val=0;\n for(auto i : tasks)\n val=max(val,i[1]);\n return max(ans+diff,val);\n }\n};\n```\nUpdate Answer : Sort based on difference and then find the maximum energy required.\n```\nclass Solution {\npublic:\n int minimumEffort(vector<vector<int>>& tasks) {\n for(auto &task : tasks)\n task[0]=task[1]-task[0];\n sort(tasks.begin(),tasks.end());\n int res=0;\n for(auto &task : tasks){\n int actual=task[1]-task[0];\n res+=actual;\n if(task[1]>res)\n res=task[1];\n }\n return res;\n }\n};\n``` | 8 | 2 | ['C'] | 3 |
minimum-initial-energy-to-finish-tasks | [C++] Greedy Solution Simple and Clear Explanation | c-greedy-solution-simple-and-clear-expla-3uec | Let\'s break the problem into two parts:\n1. Ordering the tasks\n2. Calculating the tasks\n\n1. Ordering the tasks\n\nIntuition:\nConsider a particular task, wh | arnabsen1729 | NORMAL | 2020-11-22T04:37:26.474507+00:00 | 2020-11-22T04:47:17.955929+00:00 | 442 | false | Let\'s break the problem into two parts:\n1. Ordering the tasks\n2. Calculating the tasks\n\n**1. Ordering the tasks**\n\n**Intuition:**\nConsider a particular task, which has `A` actual energy required and `M` minimum energy required. So, in order to complete this task we need to provide atleast `M` energy. But `M-A` will get wasted. Since our prime objective is to minimise this wastage, we will first solve those tasks which encurrs minimum wastage, and so on. Basically we need to sort the tasks in ascending order of `M-A`. Now our ordering part is complete. \n\nThe code for this part would be \n\n>N.B: There can be more optimised way to achieve this, but in contest this was the first method that came to my mind. \n\n```cpp\n\tvector<pair<int, int>> vp;\n\tfor(int i=0; i<n; i++){\n\t\tvp.push_back({tasks[i][1]-tasks[i][0], i});\n\t}\n\tsort(vp.begin(), vp.end());\n```\n\n**2. Calculating the energy**\n\nCreate a variable called `energy=0` which is the energy required to solve the tasks so far.Now iterate through the ordered tasks. At each task, we will compare the `energy+actual` so far with the `minimum` energy needed for the task:\n\tThere can be two outcome, \n\t\t1. `energy+actual` >`minimum` : This way we will just add the actual to the energy. `energy += actual`. Reason being if we had `energy+actual` for this task it will need `actual` to solve it and we will be left with `energy` which satisfies our assumption\n\t\t2. Else, we will make `energy=minimum`.For obvious reasons, cause otherwise we won\'t be able to complete this task\n```cpp\n\t\tint cost = tasks[(vp[0].second)][1];\n for(int i=1; i<n; i++){\n cost += tasks[vp[i].second][0];\n cost = max(cost, tasks[vp[i].second][1]);\n }\n \n return cost;\n```\n\nPutting everything together:\n\n```cpp\nclass Solution {\npublic:\n int minimumEffort(vector<vector<int>>& tasks) {\n int n=tasks.size();\n vector<pair<int, int>> vp;\n for(int i=0; i<n; i++){\n vp.push_back({tasks[i][1]-tasks[i][0], i});\n }\n \n sort(vp.begin(), vp.end());\n int cost = tasks[(vp[0].second)][1];\n // cout<<cost<<"\\n";\n for(int i=1; i<n; i++){\n // cout<<tasks[vp[i].second][1]<<", ";\n cost += tasks[vp[i].second][0];\n cost = max(cost, tasks[vp[i].second][1]);\n }\n \n return cost;\n }\n};\n```\n\nStatus: **All test case passed** | 5 | 0 | ['Greedy', 'Sorting'] | 2 |
minimum-initial-energy-to-finish-tasks | Python 3 | Sort + Greedy & Sort + Binary Search | Explanation | python-3-sort-greedy-sort-binary-search-uw5fj | Approach \#1 - Binary Search\n- Sort by difference\n- Use binary search validate if given input (energy) can finish all works\n- Search the smallest possible (l | idontknoooo | NORMAL | 2020-11-22T05:42:41.184171+00:00 | 2020-11-22T05:42:41.184213+00:00 | 470 | false | ### Approach \\#1 - Binary Search\n- Sort by difference\n- Use binary search validate if given input (energy) can finish all works\n- Search the smallest possible (like `bisect_left`)\n```\nclass Solution:\n def minimumEffort(self, tasks: List[List[int]]) -> int:\n tasks.sort(key=lambda x: x[0]-x[1])\n def ok(mid):\n for actual, minimum in tasks:\n if minimum > mid or actual > mid: return False\n if minimum <= mid: mid -= actual\n return True\n l, r = 0, 10 ** 9\n while l <= r:\n mid = (l+r) // 2\n if ok(mid): r = mid - 1\n else: l = mid + 1\n return l\n```\n\n### Approach \\#2 - Greedy\n- Sort by difference\n- `cur`: actual cost, `ans` adjust by `minimum` so that it can start for all works\n```\nclass Solution:\n def minimumEffort(self, tasks: List[List[int]]) -> int:\n tasks.sort(key=lambda x: x[0]-x[1])\n ans = cur = 0\n for cost, minimum in tasks:\n ans = min(cur-minimum, ans)\n cur -= cost\n return -ans\n``` | 4 | 0 | ['Binary Search', 'Greedy', 'Python', 'Python3'] | 1 |
minimum-initial-energy-to-finish-tasks | C++ | Beast 100% | Explained Properly | Simple Binary Search | c-beast-100-explained-properly-simple-bi-11sq | IntuitionThe goal is to find the smallest amount of energy to start with so that you can complete all tasks in some order.The key idea is:
Some tasks are harder | AK200199 | NORMAL | 2025-03-24T21:05:04.259396+00:00 | 2025-03-24T21:05:04.259396+00:00 | 34 | false | # Intuition
The goal is to find the smallest amount of energy to start with so that you can complete all tasks in some order.
The key idea is:
Some tasks are harder to start (high minimum) but don’t cost much (actual).
These tasks should be done earlier, while you still have enough energy.
# Approach
1.)Sort the tasks in descending order of (minimum - actual):
--> This ensures we handle strict/energy-demanding tasks first.
--> The intuition is: harder-to-start tasks are done early while we have high energy.
2.) Use Binary Search to find the minimum initial energy:
Search space is between 0 and a large upper bound (e.g., 1e9).
For each energy guess (mid), simulate going through tasks in sorted order:
Check if energy at every step is ≥ task’s minimum.
If yes, it's a valid starting energy → try smaller value.
If not, try a larger one.
# Complexity
- Time complexity:
O(nlogM)
- Space complexity:
O(1)
# Code
```cpp []
class Solution {
public:
// The logic is simple we do the task according to the order of minimum-actual means we do that task first which has more diff. We are doing this bcz the task with more diff requires more energy to finish take an example as [16,18],[2,16] if we did 1st task then we can't do 2nd but if 2nd done then we can do 1st with energy as 20
int minimumEffort(vector<vector<int>>& tasks) {
// Sort according to diff
sort(tasks.begin(), tasks.end(), [](vector<int>& a, vector<int>& b){
return a[1] - a[0] > b[1] - b[0];
});
// Binary search on answer
int l = 0, h = 1e9, ans = 0;
while(l <= h){
int m = l + (h - l) / 2;
int e = m;
bool ok = 1;
for(auto& t : tasks){
if(e < t[1]){
ok = 0;
break;
}
e -= t[0];
}
// if possible means we can do it in more less energy
if(ok){
ans = m;
h = m - 1;
}else{
l = m + 1;
}
}
return ans;
}
};
``` | 3 | 0 | ['Array', 'Binary Search', 'Sorting', 'C++'] | 0 |
minimum-initial-energy-to-finish-tasks | Greedy with Formal proof of correctness | greedy-with-formal-proof-of-correctness-e4wgf | As many of you may have found out the greedy strategy of doing those tasks first which have maximum minimum_{i} - actual_{i} yields the optimal solution, but wh | sanky29 | NORMAL | 2022-12-23T19:40:08.926565+00:00 | 2022-12-24T13:47:38.503881+00:00 | 610 | false | As many of you may have found out the greedy strategy of doing those tasks first which have maximum $$minimum_{i} - actual_{i}$$ yields the optimal solution, but why?\n\nWhen we start to solve the questions we try to find some pattern in it and see if dynamic programming, divide and conquer, backtracking, etc. will work or not. And at the end, we try to see if the greedy approach works or not. All the methods have very straightforward ways of proving the correctness except greedy algorithms. In this post, I would like to take this question as an example and prove formally why will it work.\nWe will divide the proof into 3 parts:\n1. Developing **Notations**\n2. Stating and proving **Exchange lemma**\n3. Using **Induction** to prove final correctness\n\n# Notations\nWe define tasks as set $$T = \\{t_{i} \\ | \\ i = 1,2,..n\\}$$ and each task is defined as $$t_{i} = [R_{i}, M_{i}]$$ where $$R_{i}$$ is required energy to complete and $$M_{i}$$ is minimum required energy to start and $$R_{i}, M_{i} > 0$$. \nNow we define a valid solution $$S$$ as ordered set $$S = \\{e^S_{1},e^S_{2},...,e^S_{n}\\}$$. Note that a valid solution satisfies all the constraints but it may not be optimal. \nWe also define set of first greedy step tasks as $$G_{1} = \\{i \\ | \\ (M_{i} - R_{i}) \\geq (M_{j} - R_{j}) \\ \\forall \\ j \\in \\{1,2,..,n\\}\\}$$. We define optimal solution $$OS$$ which has an initial energy requirement denoted as $$E_{0}^{OS}$$ minimum. $$ OS \\in argmin_{S} \\ E_{0}^{S}$$. (As argmin can be set). We also define energy after completing $$i$$ tasks of solution as $$E_{i}^S$$\n\n# Exchange Lemma\nNow we define the following lemma \n***Lemma:*** *For any valid solution $$S$$ which does not choose first task greedily that is $$e_1^S \\notin G_1$$ there exist valid $$S\'$$ which takes first task greedily that is $$e_1^{S\'} \\in G_1$$ and is at least as good as $$S$$ that is $$E_{0}^{S\'} \\le E_{0}^S$$*.\n***Proof:*** Let $$e^S_{i}$$ be the first task in $$S$$ which belongs to $$G_{1}$$ that is $$e^{S}_i \\in G_{1}$$. Now as $$S$$ is the valid solution we can say that \n$$E_0^S \\ge M_{e^S_1}$$\nWe can also write this as \n$$E_{0}^S = M_{e^S_1} + \\delta$$ where $$\\delta \\ge 0$$. \nNow lets find $$E^S_{1}$$. As $$R_{e_{1}^S}$$ amount will be used to do task $$t_{e^S_1}$$ then \n$$E_1^S = E_{0}^S - R_{e_{1}^S}$$\nAlso as $$S$$ is valid solution we have \n$$E_1^S \\ge M_{e_{2}^S}$$\nBy substituting for $$E_1^S$$ we get \n$$ E_{0}^S - R_{e_{1}^S} \\ge M_{e_{2}^S}$$\nNow extending same idea to obtain constraint equation for for $$k^{th}$$ task of $$S$$ we will bet\n$$E_{k-1}^S \\ge M_{e_{k}^S}$$\nAnd $$E_k^S$$ will be\n$$E_{k-1}^S = E_{0}^S - \\sum_{p=1}^{k-1} R_{e_{p}^S}$$\nSo final constraint will be\n$$E_{0}^S - \\sum_{p=1}^{k-1} R_{e_{p}^S} \\ge M_{e_{k}^S}$$\nNow find constraint at $$i^{th}$$ task of $$S$$ which belongs to $$G_{1}$$.\n$$E_{0}^S - \\sum_{p=1}^{i-1} R_{e_{p}^S} \\ge M_{e_{i}^S}$$\nNow lets subtract $$R_{e_{i}^S}$$ from both side\n$$E_{0}^S - \\sum_{p=1}^{i-1} R_{e_{p}^S} - R_{e_{i}^S} \\ge M_{e_{i}^S }-R_{e_{i}^S}$$\nBut by definition of $$G_1$$ we know that\n$$ M_{e_{i}^S }-R_{e_{i}^S} \\geq M_{e_{j}^S }-R_{e_{j}^S} \\ \\forall \\ j \\in \\{1,2,..,n\\} $$\nSo we get\n$$E_{0}^S - \\sum_{p=1}^{i-1} R_{e_{p}^S} - R_{e_{i}^S} \\ge M_{e_{j}^S }-R_{e_{j}^S} \\ \\forall \\ j \\in \\{1,2,..,n\\} $$\nAnd by rearranging the terms we get\n$$E_{0}^S - \\sum_{p=1}^{i-1} R_{e_{p}^S} - R_{e_{i}^S} + R_{e_{j}^S} \\ge M_{e_{j}^S } \\ \\forall \\ j \\in \\{1,2,..,n\\} $$\nCall this expression as $$A$$\nNow we construct new solution $$S\'$$ which takes first task $$t_{e^S_i}$$ but then follow $$S$$. In other words\n$$e_{1}^{S\'} = e_{i}^S$$\n$$e_{j}^{S\'} = e_{j-1}^S \\ \\forall j \\in \\{2,3,...,i\\}$$\n$$e_{j}^{S\'} = e_{j}^S \\ \\forall j \\in \\{i+1,...,n\\}$$\nIf we start with initial energy $$E_0^{S\'} = E_0^{S}$$ then this is also a valid solution. To show these let\'s consider the constraints at each task of $$S\'$$.\n1. $$e_{0}^{S\'}$$:\nWe know that (from $$S$$ being valid solution)\n$$E_{0}^S - \\sum_{p=1}^{i-1} R_{e_{p}^S} \\ge M_{e_{i}^S}$$\nAs $$R_{i} > 0$$\n$$E_{0}^S > M_{e_{i}^S}$$\nBy definition of $$S\'$$ we have\n$$E_{0}^{S\'} > M_{e_{0}^{S\'}}$$\n2. $$e_{j}^{S\'} \\ \\forall \\ j \\in \\{2,..,i\\}$$:\nNow we know that form $$A$$\n$$E_{0}^S - \\sum_{p=1}^{i-1} R_{e_{p}^S} - R_{e_{i}^S} + R_{e_{j-1}^S} \\ge M_{e_{j-1}^S } \\ \\forall \\ j \\in \\{2,..,i\\} $$\nAs $$R_{*} > 0$$ we can write this as\n$$E_{0}^S - \\sum_{p=1}^{j-1} R_{e_{p}^S} - R_{e_{i}^S} + R_{e_{j-1}^S} \\ge M_{e_{j-1}^S } \\ \\forall \\ j \\in \\{2,..,i\\} $$\n$$E_{0}^S - \\sum_{p=1}^{j-2} R_{e_{p}^S} - R_{e_{i}^S} \\ge M_{e_{j-1}^S } \\ \\forall \\ j \\in \\{2,..,i\\} $$\nUsing definition of $$S\'$$ we get\n$$E_{0}^{S\'} - \\sum_{p=2}^{j-1} R_{e_{p}^{S\'}} - R_{e_{1}^{S\'}} \\ge M_{e_{j}^{S\'} } \\ \\forall \\ j \\in \\{2,..,i\\} $$\n$$E_{0}^{S\'} - \\sum_{p=1}^{j-1} R_{e_{p}^{S\'}} \\ge M_{e_{j}^{S\'} } \\ \\forall \\ j \\in \\{2,..,i\\} $$\n3. $$e_{j}^{S\'} \\ \\forall \\ j \\in \\{i+1,..,n\\}$$:\nFrom validity of $$S$$ we get\n$$E_{0}^S - \\sum_{p=1}^{j-1} R_{e_{p}^S} \\ge M_{e_{j}^S} \\ \\forall j \\in \\{i+1,..,n\\}$$\n$$E_{0}^S - \\sum_{p=1}^{i-1} R_{e_{p}^S} - R_{e_{i}^S} -\\sum_{p=i+1}^{j-1} R_{e_{p}^S} \\ge M_{e_{j}^S} \\ \\forall j \\in \\{i+1,..,n\\}$$\nFrom definition of $$S\'$$ we get \n$$E_{0}^{S\'} - \\sum_{p=2}^{i} R_{e_{p}^{S\'}} - R_{e_{1}^{S\'}} -\\sum_{p=i+1}^{j-1} R_{e_{p}^{S\'}} \\ge M_{e_{j}^{S\'}} \\ \\forall j \\in \\{i+1,..,n\\}$$\n$$E_{0}^{S\'} - \\sum_{p=1}^{j-1} R_{e_{p}^{S\'}} \\ge M_{e_{j}^{S\'}} \\ \\forall j \\in \\{i+1,..,n\\}$$\n\nSo we proved that there exists $$S\'$$ which takes the first step greedily and does better than $$S$$. ( As $$E_{0}^{S\'} = E_{0}^{S} \\geq E_{0}^{S})$$\n\n# Induction\n**Lemma:** Greedy solution is the optimal solution\n**Proof:**\n*Base Case:* for $$n = 1$$ this is true\n*Inductive Hypothesis:* for $$\\forall n \\leq k$$ lemma holds true\n*Induction Step:* Consider problem $$T$$ of size $$n = k+1$$. Now let $$GS(T)$$ be greedy solution of $$T$$. Which can be written as\n$$GS(T) = g \\cup GS(T\')$$, where $$g$$ is first greedy task. $$T\'$$ is reduced problem of size $$k$$. Now let $$OS(T)$$ be any valid solution on the $$T$$. We construct a new valid solution $$OS\'(T)$$ same as the exchange lemma, which can also be written as $$OS\'(T) = g \\cup OS(T\')$$ From the exchange lemma we get $$E_{0}^{OS\'(T)} \\leq E_{0}^{OS(T)}$$. Now from the induction hypothesis, we know that $$E_{0}^{GS(T\')} \\leq E_{0}^{OS(T\')}$$. Hence we conclude that\n$$E_{0}^{GS(T)} \\leq E_{0}^{OS\'(T)} \\leq E_{0}^{OS(T)}$$. \n\n\n\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n\\log (n))$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n# Code\n```\nclass Solution {\npublic:\n int minimumEffort(vector<vector<int>>& tasks) {\n vector<pair<int,int>> t;\n for(auto i: tasks){\n t.push_back(make_pair(i[0] - i[1], -1*i[1]));\n }\n sort(t.begin(), t.end());\n int a = t[0].first - t[0].second;\n int r = -1*t[0].second;\n for(int i = 1; i < tasks.size(); i++){\n r = max(r, a + -1*t[i].second);\n a += t[i].first - t[i].second;\n }\n return r;\n }\n};\n```\n | 3 | 0 | ['C++'] | 2 |
minimum-initial-energy-to-finish-tasks | JAVA | java-by-lankesh-rhoc | This question revolves around finding minimum cost to complete all the task\nWe we will use the idea of sorting according to difference of Minimum - actual\nin | lankesh | NORMAL | 2022-01-08T07:20:43.866837+00:00 | 2022-01-08T07:20:43.866870+00:00 | 395 | false | This question revolves around finding minimum cost to complete all the task\nWe we will use the idea of sorting according to difference of ```Minimum - actual```\nin Descending order. \nThis will help us in setting the initial value for energy required in such \na way that left over after using the energy can be used for further demands and if further demand\nis not fulfilled, update the ```cur``` and ```initial``` requirement so that we can reach minimum\nrequirement of task.\nrepeat above process to finish all task....\nTime Complexity : ```O(NlogN)```\nUpvote if you like my explanation....!!!!\n\n```class Solution {\n public int minimumEffort(int[][] tasks) {\n Arrays.sort(tasks,new Comparator<int[]>(){\n public int compare(int[] a,int[] b){\n if((a[1] - a[0]) > (b[1] - b[0]))\n return -1;\n else return 1;\n }\n });\n int initial = tasks[0][1];\n int cur = initial;\n for(int i[] : tasks){\n if(cur >= i[1]){\n cur -= i[0];\n }\n else{\n initial = initial + i[1] - cur;\n cur = i[1]-i[0];\n }\n } \n return initial;\n \n }\n} | 3 | 0 | ['Java'] | 1 |
minimum-initial-energy-to-finish-tasks | Greedy Algorithm with FULL and EASY Explanation with NO fancy ideas or concepts!!!!! | greedy-algorithm-with-full-and-easy-expl-0wg4 | The most critical part of greedy algorithm is why we sort the array by its minimum - cost (that is tasks[i][1] - tasks[i][0]) value? If people understand this t | yuandong-chen | NORMAL | 2020-11-27T19:44:50.604609+00:00 | 2020-11-29T01:01:49.052622+00:00 | 588 | false | The most critical part of greedy algorithm is why we sort the array by its `minimum - cost (that is tasks[i][1] - tasks[i][0])` value? If people understand this trick, the leftover is nothing but iteration. \n\nFirstly, please read the question **course scheduler III**: https://leetcode.com/problems/course-schedule-iii/ (**Read question only. Don\'t read the approach first**)\n\n**Do you notice the similarity between these two questions?** \nThe minimum energy requirement for each task is equivalent to the following condition: \n* The energy after taking this task is no less than minimum - cost\n\nIf we treat the energy as time (our time goes from higher to lower, but it doesn\'t matter), this condition is basically saying \n* this task (course) should be taken no later than time = minimum - cost.\n\nOk, now we find that these two questions **are almost the same.**\n\nSecondly, please understand the following part in approach 2 explanation for course scheduler III.\n\n* From the above example, we can conclude that it is always profitable to take the course with a smaller end day prior to a course with a larger end day. This is because, the course with a smaller duration, if can be taken, can surely be taken only if it is taken prior to a course with a larger end day.\n\nThis sentance is basically saying we could sort our array by `minimum - cost (that is tasks[i][1] - tasks[i][0])` and take tasks one by one with the order. Then, here comes our greedy solution: \n\n```\nclass Solution {\n public int minimumEffort(int[][] tasks) {\n Arrays.sort(tasks, (a, b) -> b[1] - b[0] - (a[1] - a[0]));\n int ans = 0, cur = 0, len = tasks.length;\n for(int i = 0; i < len; i++) {\n if(cur < tasks[i][1]) {\n ans += tasks[i][1] - cur;\n cur = tasks[i][1] - tasks[i][0];\n }\n else {\n cur -= tasks[i][0];\n }\n }\n return ans;\n }\n}\n```\nBonus part: **course scheduler III** is a really good question that you must remember because it is not a normal matroid structure (why it is not matroid? Please refer to \u201CIntroduction to Algorithms\u201C Third edition, Introduction part of 16.4 Matroids and greedy methods. This kind problem is activity selection problem). | 3 | 0 | [] | 0 |
minimum-initial-energy-to-finish-tasks | [Python] Greedy, sort first by gap, then by required start energy | python-greedy-sort-first-by-gap-then-by-7w4ze | Not exactly sure why this works, but we know that we probably want to do the tasks with small gaps last, and the tasks with the largest required start energy fi | raymondhfeng | NORMAL | 2020-11-22T04:01:40.553189+00:00 | 2020-11-22T04:01:40.553230+00:00 | 327 | false | Not exactly sure why this works, but we know that we probably want to do the tasks with small gaps last, and the tasks with the largest required start energy first. \n\n```\nclass Solution:\n def minimumEffort(self, tasks: List[List[int]]) -> int:\n tasks.sort(key = lambda x: (-(x[1]-x[0]),-x[1]))\n curr = 0\n for i in range(len(tasks))[::-1]:\n actual,needed = tasks[i]\n curr = max(actual+curr,needed)\n \n return curr\n``` | 3 | 0 | [] | 0 |
minimum-initial-energy-to-finish-tasks | C++ | greedy solution with Intution for sorting | c-greedy-solution-with-intution-for-sort-x9fw | Intuition1st Intution :After observation, I take the sum of all the the actual time, then one by one check for each task the answer, if we take the task in last | UKS_28 | NORMAL | 2025-01-16T03:49:19.465778+00:00 | 2025-01-16T03:49:19.465778+00:00 | 104 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
### 1st Intution :
After observation, I take the sum of all the the actual time, then one by one check for each task the answer, if we take the task in last. If we take a task_i in last then we will not take the actual_time[i] of that task instead we will take the minimum_time[i], so the answer will be min(sum(actual_time)- actual_time[i] + minimum_time[i]).
But this approach was wrong, as we are not checking the middle state. what will happen for case like below:
[[1,1],[1,3]], it will give answer 2, but the actual answer is 3.
This lead to reach conclusion we need some order i.e. we need to sort in some order.
### 2nd Intution :
Continuing with previous approach, We just need to find out at any middle state ,if we are getting result, We have to find out a order.
After observation, we need to process the task first whose actual_time + the minimum_time of the next task is minimum. i.e. a[0] + b[1] < b[0] + a[1]. or we can a[0] - a[1] < b[0] - b[1].
In this way we will figure out for each task what might be the maximum answer, our result will be maximum of all these time.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
$$O(n*logn)$$
# Code
```cpp []
class Solution {
public:
static bool cmp(vector<int> &a, vector<int> &b){
return a[0] + b[1] < b[0] + a[1];
}
int minimumEffort(vector<vector<int>>& tasks) {
sort(tasks.begin(), tasks.end(), cmp);
long long res = -1e10;
long long ps = 0;
for(int i = 0; i < tasks.size(); i++){
res = max(res, ps + tasks[i][1]);
ps +=tasks[i][0];
}
return res;
}
};
``` | 2 | 0 | ['Greedy', 'Sorting', 'C++'] | 0 |
minimum-initial-energy-to-finish-tasks | Easy C++ solution || Greedy Approach | easy-c-solution-greedy-approach-by-bhara-nqij | \n\n# Code\n\nclass Solution {\npublic:\n static bool cmp(vector<int>& a, vector<int>& b){\n return (a[1] - a[0]) > (b[1] - b[0]);\n }\n\n int m | bharathgowda29 | NORMAL | 2024-01-04T07:38:20.042119+00:00 | 2024-01-04T07:38:20.042140+00:00 | 255 | false | \n\n# Code\n```\nclass Solution {\npublic:\n static bool cmp(vector<int>& a, vector<int>& b){\n return (a[1] - a[0]) > (b[1] - b[0]);\n }\n\n int minimumEffort(vector<vector<int>>& tasks) {\n sort(tasks.begin(), tasks.end(), cmp);\n int n = tasks.size(), ans = 0, energyLeft = 0;\n for(int i=0; i<n; i++){\n int actual = tasks[i][0];\n int mini = tasks[i][1];\n\n if(energyLeft < mini){\n ans += mini - energyLeft;\n energyLeft = mini - actual;\n }\n else{\n energyLeft = energyLeft - actual;\n }\n }\n\n return ans;\n }\n};\n``` | 2 | 0 | ['Array', 'Greedy', 'Sorting', 'C++'] | 0 |
minimum-initial-energy-to-finish-tasks | ✔️✔️[C++] Explained using Priority queue Simple solution | c-explained-using-priority-queue-simple-9utr7 | \nstruct Compare {\n bool operator()(pair<int,int> &a, pair<int,int> &b){\n return a.first-a.second < b.first-b.second;\n }\n};\n\nclass Solution { | am_aakash | NORMAL | 2023-02-04T13:02:58.584281+00:00 | 2023-02-04T13:02:58.584317+00:00 | 341 | false | ```\nstruct Compare {\n bool operator()(pair<int,int> &a, pair<int,int> &b){\n return a.first-a.second < b.first-b.second;\n }\n};\n\nclass Solution {\npublic:\n int minimumEffort(vector<vector<int>>& tasks) {\n priority_queue<pair<int,int>, vector<pair<int,int>>, Compare> pq;\n // sorted for max abs difference of [minimum, actual]\n for(auto v:tasks) pq.push({v[1], v[0]});\n int res = 0, curr = 0; // curr min energy\n\n while(!pq.empty()){\n if(pq.top().first > curr) // minimum energy reqd > curr energy\n res += (pq.top().first-curr), // res += difference to add\n curr = pq.top().first; // curr energy set\n \n curr -= pq.top().second; // using the actual from curr energy\n\n pq.pop();\n }\n return res;\n }\n};\n``` | 2 | 0 | ['Greedy', 'Heap (Priority Queue)', 'C++'] | 0 |
minimum-initial-energy-to-finish-tasks | Sort + memoization C++ using greedy approach | sort-memoization-c-using-greedy-approach-oam0 | Intuition\n- We need to prioritise doing tasks first which has higher difference actual and minimum energy. \n- Because they have high barrier (minimum energy) | him500 | NORMAL | 2022-12-25T12:54:05.709126+00:00 | 2022-12-25T12:54:05.709161+00:00 | 499 | false | # Intuition\n- We need to prioritise doing tasks first which has higher difference actual and minimum energy. \n- Because they have high barrier (minimum energy) but low actual energy as compared to min energy so we need to prioritise them. \n- One way is to sort them by their difference.\n\n# Complexity\n- Time complexity: O(nlogn)\n- Space complexity: O(n)\n\n# Approach 1\nMemoization\n\n# Code\n```\nclass Solution {\npublic:\n static const bool cmp(vector<int>& a, vector<int>& b){\n return a[1] - a[0] > b[1] - b[0];\n }\n int dp[100001];\n int solve(vector<vector<int>>& tasks, int i){\n if(i == tasks.size()) return 0;\n if(dp[i] != -1) return dp[i];\n\n int ans = tasks[i][1];\n int take = tasks[i][0] + solve(tasks, i+1);\n\n return dp[i] = max(take, ans);\n }\n int minimumEffort(vector<vector<int>>& tasks) {\n sort(tasks.begin(), tasks.end(), cmp);\n memset(dp, -1, sizeof dp);\n return solve(tasks, 0);\n }\n};\n```\n\n# Approach 2\nTabutation\n\n# Code\n```\nclass Solution {\npublic:\n static const bool cmp(vector<int>& a, vector<int>& b){\n return a[1] - a[0] > b[1] - b[0];\n }\n int minimumEffort(vector<vector<int>>& tasks) {\n sort(tasks.begin(), tasks.end(), cmp);\n int n = tasks.size();\n \n int dp[n+1];\n memset(dp, 0, sizeof dp);\n for(int i=tasks.size()-1; i>=0; i--) {\n dp[i] = max(tasks[i][0] + dp[i+1], tasks[i][1]);\n }\n return dp[0];\n }\n};\n``` | 2 | 0 | ['Dynamic Programming', 'Greedy', 'Memoization', 'C++'] | 1 |
minimum-initial-energy-to-finish-tasks | Greedy solution, sorting | greedy-solution-sorting-by-prashant18253-sf3x | Sort the array on the basis of the difference between the threshold and actual energy.\n\nimport java.util.*;\nclass Solution {\n public int minimumEffort(in | prashant18253 | NORMAL | 2021-06-27T09:01:51.429179+00:00 | 2021-06-27T09:01:51.429213+00:00 | 238 | false | Sort the array on the basis of the difference between the threshold and actual energy.\n```\nimport java.util.*;\nclass Solution {\n public int minimumEffort(int[][] tasks)\n {\n Arrays.sort(tasks, new Comparator<int[]>(){\n @Override\n public int compare(int[] a, int[] b)\n {\n return (b[1]-b[0])-(a[1]-a[0]);\n }\n });\n int sum=0, max=0;\n for(int i=0;i<tasks.length;i++)\n {\n max=Math.max(max, sum+tasks[i][1]);\n sum+=tasks[i][0];\n }\n \n return max;\n \n }\n}``` | 2 | 0 | ['Sorting', 'Java'] | 0 |
minimum-initial-energy-to-finish-tasks | Proof of the greedy approach | proof-of-the-greedy-approach-by-wutongth-nbu9 | Suppose the energe we have before starting is E, and the order of the taskes is (a[0], m[0]), ... (a[n-1], m[n-1])\n\nE should satisfy the following rules:\n\nE | wutongthucs | NORMAL | 2021-03-28T22:18:21.761516+00:00 | 2021-03-28T22:30:37.001039+00:00 | 205 | false | Suppose the energe we have before starting is E, and the order of the taskes is ```(a[0], m[0]), ... (a[n-1], m[n-1])```\n\nE should satisfy the following rules:\n```\nE >= m[0],\nE >= a[0] + m[1],\n...\nE >= sum(a[0:i)) + m[i]\n...\n```\n\nLet ```c[i] = sum(a[0:i)) + m[i]```, we would have ```E >= max(c[0], c[1],.... c[n-1])```, so for a given task list, the minimum energe we need is ```max(c[0], c[1],.... c[n-1])```\n\nLet\'s now suppose the optimized solution can only be achieved when the taskes is ordered by its energe difference ```(m[i] - a[i])``` descending, if not, then there must exist a pair of neighboring task ```(i, i + 1)``` where```m[i] - a[i] < m[i+1] - a[i+1]```\n\nThen we can swap this two taskes and get a new task list and denote it as ```(a\'[i], m\'[i])```, similarly, we denote ```c\'[i]``` as ```c\'[i] = sum(a\'[0:i) + m\'[i])```, and the minumum energy ```E\'``` would be ```E\' = max(c\'[0], c\'[1], ....c\'[n-1])```\n\nAs the only difference from the new task list is the swapped two taskes, so only ```c\'[i]``` and ```c\'[i+1]``` have been changed, let\'s denote the others as ```A = {c[0], c[1], ...c[i-1], c[i+2], ..c[n-1]}```\n\nAfter some math work, we got \n```\nc\'[i] = c[i+1] - a[i] < c[i+1]\nc\'[i+1] = c[i+1] + (m[i] - a[i]) - (m[i+1] - a[i+1]) < c[i + 1]\nso max(c\'[i], c\'[i+1]) < c[i + 1] <= max(A, c[i], c[i+1]) = E \nand A <= max(A, c[i], c[i + 1]) = E\n```\nso ```E\' = max(A, c\'[i], c\'[i + 1]) <= E```, which means after swapping we can get an optimized energy as well.\n \nThe code:\n```\nclass Solution {\npublic:\n int minimumEffort(vector<vector<int>>& tasks) {\n sort(tasks.begin(), tasks.end(), [](const vector<int>& a, const vector<int>& b){\n return a[1] - a[0] > b[1] - b[0]; \n });\n\n int ans = 0;\n int s = 0;\n for (auto& t : tasks)\n {\n ans = max(ans, t[1] + s);\n s += t[0];\n }\n return ans;\n }\n};\n``` | 2 | 0 | [] | 2 |
minimum-initial-energy-to-finish-tasks | Java - with simple idea explanation | java-with-simple-idea-explanation-by-xyb-k37z | \nclass Solution {\n public int minimumEffort(int[][] tasks) {\n \n /*\n Idea - finding the minimum initial energy to finish tasks\n | xyborg | NORMAL | 2021-01-01T13:26:40.387560+00:00 | 2021-01-01T13:27:08.959945+00:00 | 263 | false | ```\nclass Solution {\n public int minimumEffort(int[][] tasks) {\n \n /*\n Idea - finding the minimum initial energy to finish tasks\n \n -> finish tasks which can induce max residual energy after completion\n eg - [5,10] over [10,10] since former can carry over energy\n and total initial energy will be - 10 +5 = 15 \n \n if we do the other way \n [10,10] [5,10] - initial energy will be 10 + 10 = 20\n \n -> if two tasks have same residual energy, order doesnt matter since the carry over is going to be same irrespective\n \n */\n \n Arrays.sort(tasks,(a,b)->{\n int diff = (b[1]-b[0]) - (a[1]-a[0]);\n return diff;\n });\n \n int initial = 0;\n int power = 0;\n \n // iterate the sorted tasks\n for(int i=0;i<tasks.length;i++)\n {\n // if existing power is less than min required - add to inital energy to supplement it from start\n if(power < tasks[i][1])\n {\n // difference requied to smoothly execute this task in ideal case\n initial+=tasks[i][1]-power;\n \n // now power is restored to min requied\n power = tasks[i][1];\n }\n \n // consume the energy for the task\n power-=tasks[i][0];\n }\n return initial;\n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
minimum-initial-energy-to-finish-tasks | Java | Greedy approach with sorting O(nlogn) | java-greedy-approach-with-sorting-onlogn-l0uh | \nclass Solution {\n public int minimumEffort(int[][] tasks) {\n Arrays.sort(tasks, (t1, t2) -> (t2[1]-t2[0]) - (t1[1]-t1[0]));\n int initial = | levimor | NORMAL | 2020-12-05T09:27:57.980489+00:00 | 2022-06-17T10:35:40.202901+00:00 | 354 | false | ```\nclass Solution {\n public int minimumEffort(int[][] tasks) {\n Arrays.sort(tasks, (t1, t2) -> (t2[1]-t2[0]) - (t1[1]-t1[0]));\n int initial = 0, current = 0;\n for (int[] task : tasks) {\n if (current < task[1]) {\n initial += task[1] - current;\n current = task[1];\n }\n current -= task[0];\n }\n return initial;\n }\n}\n``` | 2 | 0 | ['Greedy', 'Sorting', 'Java'] | 0 |
minimum-initial-energy-to-finish-tasks | C++ greedy O(n) Runtime with O(n) space and easy to understand with explanation | c-greedy-on-runtime-with-on-space-and-ea-ig6l | Intution here is we need to work on the tasks whose difference of enery to begin and energy to complete in decreasing order which allows us to spend enery more | sanjayreddy | NORMAL | 2020-11-22T17:42:15.932740+00:00 | 2020-11-22T17:42:15.932772+00:00 | 198 | false | * **Intution** here is we need to work on the tasks whose difference of enery to begin and energy to complete in decreasing order which allows us to spend enery more efficiently.\n* **Algorithm:**\n\t1. Lets first calculate total energy required to finish all the tasks ie. tasks[0][0]+tasks[1][0]+...+tasks[n-1][0]\n\t2. now lets find minimum of tasks[i][1]-tasks[i][0] i.e minimum amount of extra energy required to begin all the tasks \n\t3. Our final answer will be maximum of total_energy_required+min_diff_begin_needed and maximum of energy_required_to_begin\n```\nclass Solution {\npublic:\n int minimumEffort(vector<vector<int>>& tasks) {\n int n = tasks.size();\n int min_diff_begin_needed = INT_MAX,max_energy_required_to_begin = INT_MIN;\n int total_energy_required = 0;\n for(int i =0;i<n;i++){\n total_energy_required += tasks[i][0];\n min_diff_begin_needed = min(min_diff_begin_needed,tasks[i][1]-tasks[i][0]);\n max_energy_required_to_begin = max(max_energy_required_to_begin,tasks[i][1]);\n }\n return (total_energy_required + min_diff_begin_needed) > max_energy_required_to_begin ? (total_energy_required + min_diff_begin_needed) : max_energy_required_to_begin;\n }\n};\n``` | 2 | 0 | ['Greedy', 'C'] | 0 |
minimum-initial-energy-to-finish-tasks | Simple Python solution using sort | simple-python-solution-using-sort-by-gra-eqwz | \ndef minimumEffort(self, tasks: List[List[int]]) -> int:\n tasks.sort(key=lambda a:a[1]-a[0],reverse=True)\n res,curr=0,0\n for i,j in tas | GrandWarden | NORMAL | 2020-11-22T15:54:45.237441+00:00 | 2020-11-22T15:56:54.027853+00:00 | 79 | false | ```\ndef minimumEffort(self, tasks: List[List[int]]) -> int:\n tasks.sort(key=lambda a:a[1]-a[0],reverse=True)\n res,curr=0,0\n for i,j in tasks:\n if curr<j:\n res+=j-curr\n curr=j\n curr-=i\n return res\n``` | 2 | 0 | [] | 0 |
minimum-initial-energy-to-finish-tasks | Simplest proof of greedy correctness | simplest-proof-of-greedy-correctness-by-z9m4r | Suppose an ordering of the tasks can be completed with some initial energy; assume the ordering has consecutive tasks [a1, m1] and [a2, m2] where m1 - a1 < m2 - | subfallen | NORMAL | 2020-11-22T06:29:06.398679+00:00 | 2020-11-22T06:30:18.774071+00:00 | 77 | false | Suppose an ordering of the tasks can be completed with some initial energy; assume the ordering has consecutive tasks `[a1, m1]` and `[a2, m2]` where `m1 - a1 < m2 - a2`.\n\nWe claim we can reverse the order of these two tasks, and the result will still be completable with the same initial energy. Indeed, suppose energy `R` remains at the time of processing `[a1, m1]` in the original sequence. We only need to show that `R - a2 \u2265 m1`. By assumption we have `a2 < m2 - m1+ a1`; and thus,\n\n```\nR - a2 > R - (m2 - m1 + a1) = m1 + (R - a1 - m2) \n```\n\nBut `R - a1 \u2265 m2` because the original ordering can be completed. Hence `R - a2 > m1` and we can safely swap any such adjacent pair of tasks; which is equivalent to saying we can choose tasks in descending order of `mI - aI`. \u25A1 | 2 | 0 | [] | 0 |
minimum-initial-energy-to-finish-tasks | python3 with explaination | python3-with-explaination-by-bakerston-ez16 | Sorted tasks by the different between minimum required energy and energy cost, which is x[1]-x[0].\nKeep merging two tasks into a single task, until we only hav | Bakerston | NORMAL | 2020-11-22T04:14:19.232774+00:00 | 2020-11-22T04:14:54.183444+00:00 | 123 | false | Sorted tasks by the different between minimum required energy and energy cost, which is *x[1]-x[0]*.\nKeep merging two tasks into a single task, until we only have one task.\n\nThe cost of the combined task equals to the sum of the energy cost of two tasks.\nFor minimum required energy, lets assume we start with task1 then task2, we need to\n* energy>task1[1] \n* spend task1[0] and then have remaining energy>task2[1] satisfied. Thus for this order (t1 -> t2) we have:\n**minimum energy= max(task1[1], task1[0]+ task2[1])**, we have to meet both requirements in order to finish these two tasks in this order.\n\nHowever we can also finish the task pairs in another order, which is task2 -> task1, where the minimum energy is\n**minimum energy= max(task2[1], task2[0]+ task1[1])**\n\nTherefore for a certain task pair, the minimum energy requirement is the smaller one.\n\n\n```\ndef minimumEffort(tasks):\n def merg(t1,t2):\n return t1[0]+t2[0],min(max(t1[1]+t2[0],t2[1]),max(t1[0]+t2[1],t1[1]))\n ans=sorted(tasks,key=lambda x:x[1]-x[0])[::-1]\n return functools.reduce(merg,ans)[1]\n```\n\n\n | 2 | 0 | [] | 0 |
minimum-initial-energy-to-finish-tasks | C++ greedy solution | c-greedy-solution-by-meliky-eo45 | \nstatic bool compare(vector<int>& left, vector<int>& right){\n if(left[1] - left[0] == right[1] - right[0])\n {\n return left[0] > rig | meliky | NORMAL | 2020-11-22T04:12:16.817831+00:00 | 2020-11-22T04:12:16.817872+00:00 | 91 | false | ```\nstatic bool compare(vector<int>& left, vector<int>& right){\n if(left[1] - left[0] == right[1] - right[0])\n {\n return left[0] > right[0]; \n }\n return left[1] - left[0] < right[1] -right[0];\n }\n int minimumEffort(vector<vector<int>>& tasks) {\n sort(tasks.begin(), tasks.end(), compare);\n int energy=0;\n for(auto task : tasks){\n energy+=task[0];\n energy = max(energy, task[1]);\n }\n return energy;\n }\n``` | 2 | 0 | [] | 0 |
minimum-initial-energy-to-finish-tasks | Python Greedy 8 Lines | python-greedy-8-lines-by-sailormoons-359h | \ndef minimumEffort(self, tasks):\n\tsort = sorted(tasks, key = lambda x : x[1] - x[0])[::-1]\n\tres = 0; curr = 0\n\tfor i, n in enumerate(sort):\n\t\tif curr | SailorMoons | NORMAL | 2020-11-22T04:04:30.097104+00:00 | 2020-11-22T04:05:05.975716+00:00 | 128 | false | ```\ndef minimumEffort(self, tasks):\n\tsort = sorted(tasks, key = lambda x : x[1] - x[0])[::-1]\n\tres = 0; curr = 0\n\tfor i, n in enumerate(sort):\n\t\tif curr < n[1]:\n\t\t\tres += n[1] - curr\n\t\t\tcurr = n[1]\n\t\tcurr -= n[0]\n\treturn res\n``` | 2 | 0 | [] | 1 |
minimum-initial-energy-to-finish-tasks | Clean Java Code O(n log n) | clean-java-code-on-log-n-by-navid-y13h | \n\n public int minimumEffort(int[][] tasks) {\n List energyList = getEnergyList(tasks);\n return getMinimumRequiredEnergy(energyList);\n }\ | navid | NORMAL | 2020-11-22T04:02:28.950310+00:00 | 2020-11-22T05:55:15.489679+00:00 | 188 | false | \n\n public int minimumEffort(int[][] tasks) {\n List<Energy> energyList = getEnergyList(tasks);\n return getMinimumRequiredEnergy(energyList);\n }\n\n private int getMinimumRequiredEnergy(List<Energy> energyList) {\n int requiredEnergy = 0;\n int remainingEnergy = 0;\n for (Energy energy : energyList) {\n if (energy.minimum > remainingEnergy) {\n int d = energy.minimum - remainingEnergy;\n requiredEnergy += d;\n remainingEnergy += d;\n }\n remainingEnergy -= energy.actual;\n }\n return requiredEnergy;\n }\n\n private List<Energy> getEnergyList(int[][] tasks) {\n List<Energy> energyList = new ArrayList<>();\n for (int[] task : tasks) {\n Energy energy = new Energy(task[0], task[1]);\n energyList.add(energy);\n }\n Collections.sort(energyList);\n return energyList;\n }\n\n class Energy implements Comparable<Energy>{\n int actual;\n int minimum;\n int diff;\n\n public Energy(int actual, int minimum){\n this.actual = actual;\n this.minimum = minimum;\n diff = minimum - actual;\n }\n\n public int compareTo(Energy compareEnergy){\n int diff = compareEnergy.diff;\n int diffOfDiff = diff - this.diff;\n if(diffOfDiff == 0) {\n return this.minimum - compareEnergy.minimum;\n }\n return diff - this.diff;\n }\n } | 2 | 0 | [] | 0 |
minimum-initial-energy-to-finish-tasks | Greedy Task Energy Minimization | greedy-task-energy-minimization-by-imund-2bql | IntuitionTo minimize the initial energy needed to complete all tasks, we should order the tasks in a way that avoids having to "top up" energy unnecessarily. Ta | imundertheree | NORMAL | 2025-04-06T20:06:36.558884+00:00 | 2025-04-06T20:06:36.558884+00:00 | 9 | false | # Intuition
To minimize the initial energy needed to complete all tasks, we should order the tasks in a way that avoids having to "top up" energy unnecessarily. Tasks that have a large gap between the required minimum energy and actual effort are more restrictive and should be prioritized earlier.
# Approach
1. Sort the tasks in descending order based on the difference between minimum energy required and actual effort (i.e., `min - effort`).
2. Initialize `total_effort` and `current_energy` to 0.
3. Loop through the sorted tasks:
- If `current_energy` is less than the task's minimum required energy, increase it and add the difference to `total_effort`.
- Deduct the task’s effort from `current_energy`.
4. Return the total energy added (`total_effort`) as the final answer.
# Complexity
- Time complexity:
$$O(n \log n)$$ — due to sorting the tasks.
- Space complexity:
$$O(1)$$ — only a constant amount of space is used (no extra data structures).
# Code
```python3
class Solution:
def minimumEffort(self, tasks: list[list[int]]) -> int:
tasks.sort(key=lambda x: x[1] - x[0], reverse=True)
total_effort = 0
current_energy = 0
for effort, minimum in tasks:
if current_energy < minimum:
total_effort += minimum - current_energy
current_energy = minimum
current_energy -= effort
return total_effort
```
# Thanks for reading <3

| 1 | 0 | ['Python3'] | 0 |
minimum-initial-energy-to-finish-tasks | Beginner Friendly || Beats 100% Runtime in CPP || Easiest CPP Solution | beginner-friendly-beats-100-runtime-in-c-j8ha | IntuitionTukkaApproachBy Aman VishwakarmaComplexity
Time complexity: O(n∗logn)
Space complexity:O(1)
Code | Aman_Vi | NORMAL | 2025-04-02T18:55:55.820630+00:00 | 2025-04-02T18:55:55.820630+00:00 | 12 | false | # Intuition
Tukka
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
By Aman Vishwakarma
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity: $$O(n*logn)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:$$O(1)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
static bool comp(vector<int>&a,vector<int>&b){
return (a[1]-a[0])<(b[1]-b[0]);
}
int minimumEffort(vector<vector<int>>& tasks) {
sort(tasks.begin(),tasks.end(),comp);
int ans=0;
ans+=tasks[0][1] ;
for(int i=1;i<tasks.size();i++){
ans+=tasks[i][0];
if(ans<tasks[i][1])ans=tasks[i][1];
}
return ans;
}
};
``` | 1 | 0 | ['Array', 'Sorting', 'C++'] | 0 |
minimum-initial-energy-to-finish-tasks | Very good problem | very-good-problem-by-simolekc-ym0v | Code | simolekc | NORMAL | 2025-02-07T12:17:29.036502+00:00 | 2025-02-07T12:17:29.036502+00:00 | 7 | false |
# Code
```javascript []
/**
* @param {number[][]} tasks
* @return {number}
*/
var minimumEffort = function (tasks) {
let n = tasks.length;
tasks.sort((a, b) => a[0] - a[1] + b[1] - b[0]);
let needEnergy = -Infinity;
let used = 0;
let cost, need;
for (let i = 0; i < n; i++) {
[cost, need] = tasks[i];
needEnergy = Math.max(needEnergy, used + need);
used += cost;
}
return needEnergy;
};
``` | 1 | 0 | ['JavaScript'] | 0 |
minimum-initial-energy-to-finish-tasks | Simple math | Easy to Understand | Python | simple-math-easy-to-understand-python-by-2z4q | IntuitionBinary search is the first intutionApproachlet us take the general example of two tasks
task1 = [actual1, minimum1] and task2 = [actual2, minimum2]let | sheshankkumarsingh28 | NORMAL | 2025-01-08T11:29:38.663168+00:00 | 2025-01-08T11:29:38.663168+00:00 | 45 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
Binary search is the first intution
# Approach
<!-- Describe your approach to solving the problem. -->
let us take the general example of two tasks
task1 = [actual1, minimum1] and task2 = [actual2, minimum2]
let us first consider the case where we do task1 first and the minimum time required to complete both tasks is x
x should be greater than minimum1 and after subtracting actual1 it should be greater than minimum2, this gives us two equations
x >= minimum1 --------------------------------------->(1)
x-actual1 >= minimum2 -> x >= minimum2+actual1 --->(2)
using equation 1 and 2 we can clearly see that
x >= max(minimum1,minimum2+actual1)
similarily if we take the second case where we do task2 first and the minimum time required to complete both tasks is y
y >= max(minimum2,minimum1+actual2)
Now the question boils down to a simpler form -> find which is bigger x or y, and this can be done using a custom comparator
After sorting the tasks using this compartor the problem becomes a simple binary search 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
```python3 []
from functools import cmp_to_key
class Solution:
def minimumEffort(self, tasks: List[List[int]]) -> int:
def func(a,b):
if max(a[0],b[0]+a[1]) < max(b[0],a[0]+b[1]):
return 1
elif max(a[0],b[0]+a[1]) > max(b[0],a[0]+b[1]):
return -1
return 0
def isPossible(energy):
for i in range(n):
if energy < tasks[i][1]:
return False
energy -= tasks[i][0]
return True
n = len(tasks)
tasks.sort(key = cmp_to_key(func))
left, right = tasks[-1][-1], sum([tasks[i][1] for i in range(n)])
while left <= right:
mid = (left+right)//2
if isPossible(mid):
ans = mid
right = mid-1
else:
left = mid+1
return ans
``` | 1 | 0 | ['Python3'] | 0 |
minimum-initial-energy-to-finish-tasks | EASY AND SIMPLE JAVA SOLUTION (WITH EXPLAINATION). | easy-and-simple-java-solution-with-expla-9c09 | 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 | ManasSingh7 | NORMAL | 2024-03-20T06:50:29.895596+00:00 | 2024-03-20T06:50:29.895672+00:00 | 44 | 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 int minimumEffort(int[][] tasks) {\n Arrays.sort(tasks, (a, b) -> Integer.compare(a[1]-a[0], b[1]-b[0]));\n int ans=tasks[tasks.length-1][1];\n int diff=tasks[tasks.length-1][1]-tasks[tasks.length-1][0];\n for(int i=tasks.length-2;i>=0;i--){\n if(tasks[i][1]>diff){\n ans=ans+tasks[i][1]-diff;\n diff=tasks[i][1]-tasks[i][0];\n }\n else{\n diff=diff-tasks[i][0];\n }\n }\n return ans;\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
minimum-initial-energy-to-finish-tasks | Most Easy cpp solution(Beats 100%) | most-easy-cpp-solutionbeats-100-by-sanya-bjkf | 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 | sanyam46 | NORMAL | 2023-08-02T14:27:34.042055+00:00 | 2023-08-02T14:27:34.042080+00:00 | 137 | 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:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minimumEffort(vector<vector<int>>& tasks) \n {\n int ans = 0;\n int energy_left = 0;\n sort(tasks.begin() , tasks.end() , [&](const vector<int>& a , const vector<int>& b)\n {\n return (a[1]-a[0]) > (b[1]-b[0]) ;\n });\n //sorting algorithm to sort 2D Array\n //we have sorted the array in descending order\n\n for(vector<int> i:tasks)\n {\n const int actual = i[0];\n const int minimum = i[1];\n if(energy_left<minimum)\n {\n ans += minimum - energy_left;\n energy_left = minimum - actual;\n }\n else\n {\n energy_left = energy_left - actual;\n }\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
minimum-initial-energy-to-finish-tasks | C++✅✅ | Custom Sort | Easy Solution | Clean Code | | c-custom-sort-easy-solution-clean-code-b-6ueh | \n\n# Code\n\n\nclass Solution {\npublic:\n\nstatic bool cmp(vector<int>&v1, vector<int>&v2)\n{\n return v1[1] - v1[0] > v2[1] - v2[0];\n}\n\n int min | mr_kamran | NORMAL | 2022-11-28T04:15:07.067638+00:00 | 2022-11-28T04:15:39.921577+00:00 | 169 | false | \n\n# Code\n```\n\nclass Solution {\npublic:\n\nstatic bool cmp(vector<int>&v1, vector<int>&v2)\n{\n return v1[1] - v1[0] > v2[1] - v2[0];\n}\n\n int minimumEffort(vector<vector<int>>& tasks) {\n\n \n sort(tasks.begin(),tasks.end(),cmp);\n\n int ans = tasks[0][1];\n int temp = ans - tasks[0][0];\n\n \n for(int i = 1; i < tasks.size(); ++i)\n {\n if(temp < tasks[i][1])\n {\n ans += tasks[i][1] - temp;\n temp = tasks[i][1] - tasks[i][0];\n } \n else temp -= tasks[i][0];\n }\n \n\n return ans;\n }\n};\n\n\n``` | 1 | 0 | ['C++'] | 0 |
minimum-initial-energy-to-finish-tasks | C++ || Intuitions Explained || Binary Search || Thanks to chipbk10 | c-intuitions-explained-binary-search-tha-0bsx | \n#define ll long long\n\nclass Solution {\npublic:\n // Basically this question is based amount of profit u can get \n \n // so u want to invest on th | KR_SK_01_In | NORMAL | 2022-08-02T15:19:36.968885+00:00 | 2022-08-02T15:20:20.105062+00:00 | 143 | false | ```\n#define ll long long\n\nclass Solution {\npublic:\n // Basically this question is based amount of profit u can get \n \n // so u want to invest on those tasks where u will get more profits \n \n // so sorting must be done on the basis of differnces \n \n // take firstly those pairs which has more differnence.\n \n // This quote which is written below is from chipbk10 , all credit to him \n \n // I want to add as it clarifies problem a lot !! Thanx to him .\n \n //If you want to invest on a project [x,y], you must have y money. Once finished, you gain y-x money.\n\t//So, which project you should invest first to build up a good capital for the next investments?\n\n//My advice is to invest on projects which are able to bring back the highest profitability y-x. Even, in \n//the case y is very big, don\'t be afraid, you can loan extra money from other sources (banks, family, \n//friends) to have enough y money. The secret is you know that at this moment, y-x is the most profitable.\n\n//So, we can arrange the projects by decreasing profits, and borrow money to invest if our capital is not enough.\n \n \n static bool compare( vector<int> &a , vector<int> &b)\n {\n return (a[1]-a[0]) < (b[1]-b[0]);\n }\n \n bool func(vector<vector<int>> &nums , int mid)\n {\n int n=nums.size();\n \n for(int i=n-1;i>=0;i--)\n {\n if(mid<nums[i][1])\n {\n return false;\n }\n else\n {\n mid-=nums[i][0];\n }\n }\n \n return true;\n }\n int minimumEffort(vector<vector<int>>& nums) {\n \n sort(nums.begin() , nums.end() , compare);\n \n int n=nums.size();\n \n // We know that answer will be in the range of\n \n //Summation Minimum i - Summation actual i\n \n ll sum1=0 , sum2=0;\n \n for(int i=0;i<n;i++)\n {\n sum1+=nums[i][0];\n sum2+=nums[i][1];\n }\n \n // Apply binary search in the range\n \n ll l=sum1 , r=sum2;\n \n ll ans=sum1;\n \n while(l<=r)\n {\n ll mid=(l + (r-l)/2);\n \n if(func(nums , mid )==true)\n {\n ans=mid;\n r=mid-1;\n }\n else\n {\n l=mid+1;\n }\n }\n \n return ans;\n \n }\n``` | 1 | 0 | ['Greedy', 'C', 'Sorting', 'Binary Tree', 'C++'] | 0 |
minimum-initial-energy-to-finish-tasks | Java Solution | Binary search | Sorting | java-solution-binary-search-sorting-by-m-fgfm | Sort the array according to diffference between minimun energy and actual energy(In descending order)\n2. Calculate the sum of actual energy and sum of minimum | mihir05 | NORMAL | 2022-08-02T06:17:50.419384+00:00 | 2022-08-02T06:17:50.419430+00:00 | 202 | false | 1. Sort the array according to diffference between minimun energy and actual energy(In descending order)\n2. Calculate the sum of actual energy and sum of minimum energy i.e sum of tasks[i][0] and tasks[i][1]\n3. we know that our answer lies between these two sum, we can use binary search to find the answer, if mid is the correct answer then we need to minimize these, so we will move to left.\n4. To check the answer, check if num is less than tasks[i][1] then decrease num by tasks[i][0] otherwise return false. If we reach to the end of tasks we can say that we found the answer\n\n**Time complexity**: O(nlogn) + O(nlogn)\n**Space complexity**: O(1)\n\n```\nclass Solution {\n public int minimumEffort(int[][] tasks) {\n int start = 0;\n int end = 0;\n for(int[] task: tasks){\n start += task[0];\n end += task[1];\n }\n int res = Integer.MAX_VALUE;\n Arrays.sort(tasks, (a, b) -> { return (b[1] - b[0]) - (a[1] - a[0]);});\n System.out.println(Arrays.deepToString(tasks));\n while(start<=end){\n int mid = start + (end-start)/2;\n if(isValid(tasks, mid)){\n res = Math.min(res,mid);\n end = mid-1;\n }else{\n start = mid+1;\n }\n }\n return res;\n }\n boolean isValid(int[][] tasks, int num){\n for(int[] task: tasks){\n if(num<task[1]){\n return false;\n }\n num -= task[0];\n }\n return true;\n }\n} | 1 | 0 | ['Sorting', 'Binary Tree', 'Java'] | 0 |
minimum-initial-energy-to-finish-tasks | Java || Greedy || O(N logN ) time || O(1) space | java-greedy-on-logn-time-o1-space-by-nam-2yaz | sort it by difference between minimum energy and needed energy\n```\nclass Solution {\n public int minimumEffort(int[][] tasks) {\n Arrays.sort(tasks, | namansachan7 | NORMAL | 2022-03-12T08:10:05.079843+00:00 | 2022-03-12T08:10:05.079893+00:00 | 190 | false | sort it by difference between minimum energy and needed energy\n```\nclass Solution {\n public int minimumEffort(int[][] tasks) {\n Arrays.sort(tasks,(a,b)->a[1]-a[0]-b[1]+b[0]);\n int prev=0;\n for (int[] item:tasks){\n prev=Math.max(prev+item[0],item[1]);\n }\n return prev;\n }\n} | 1 | 0 | ['Greedy', 'Sorting', 'Java'] | 0 |
minimum-initial-energy-to-finish-tasks | Simple 4-line solution, faster than 80% | simple-4-line-solution-faster-than-80-by-bxui | Key Insight\n\nWanting the smallest possible starting value is the same as wanting the smallest possible ending value.\n\n# Algorithm\nTherefore sort the tasks | darrelfrancis | NORMAL | 2021-11-19T08:05:02.894870+00:00 | 2021-11-19T08:06:12.219811+00:00 | 175 | false | # Key Insight\n\nWanting the smallest possible _starting_ value is the same as wanting the smallest possible _ending_ value.\n\n# Algorithm\nTherefore sort the tasks in order of what is the smallest possible energy value that can exist after the task runs. This is _minimum MINUS actual_.\n\nThen loop through the sorted tasks, starting from the smallest possible ending value. [This is equivalent to playing back a movie of the optimal solution, starting from the end of the movie.]\n\nStart the loop (i.e. the end of the movie) with an optimistic hope that you might need zero energy at that time point. \n\nAt every task (as you loop backwards through the movie of optimally arranged tasks):\n* if the task needs to end with more energy than you currently have, increase the energy to match that requirement\n* add the actual energy used by the task\nThis gives the minimum amount of energy that was needed _before_ this task.\n\nOnce you have looped through all, that energy value you have been cumulating, is now the minimum needed for the entire group of tasks.\n\n\n```\nclass Solution:\n def minimumEffort(self, tasks: List[List[int]]) -> int:\n \n tasks.sort(key = lambda task:task[1]-task[0])\n \n energy = 0\n for task in tasks:\n energy = max(energy, task[1]-task[0]) + task[0]\n \n return energy\n```\n\n\n# Please LIKE if it helped you! 8-) | 1 | 0 | ['Python'] | 0 |
minimum-initial-energy-to-finish-tasks | Python, sort then dp | python-sort-then-dp-by-404akhan-mj35 | Sort by minimum_i - actual_i, then do dp.\n\nYou can show that if you have minimum_i - actual_i not in sorted order, you can swap them and using bubble sort eve | 404akhan | NORMAL | 2021-11-17T14:08:52.818547+00:00 | 2021-11-17T14:08:52.818587+00:00 | 120 | false | Sort by `minimum_i - actual_i`, then do dp.\n\nYou can show that if you have `minimum_i - actual_i` not in sorted order, you can swap them and using bubble sort eventually sort them and still have valid solution (with same initial amount of energy). Just write down inequalities.\n\nNow after sorting we get easy dp, where at step `i` we need to have `max(minimum_i, actual_i + dp[i + 1])` energy to finish remaining tasks.\n\n\n```\nclass Solution:\n def minimumEffort(self, tasks) -> int:\n n = len(tasks)\n tasks.sort(key=lambda p: -p[1] + p[0])\n dp = [0] * n\n dp[-1] = max(tasks[-1][1], tasks[-1][0])\n for i in range(n - 2, -1, -1):\n dp[i] = max(tasks[i][1], tasks[i][0] + dp[i + 1])\n return dp[0]\n``` | 1 | 0 | [] | 0 |
minimum-initial-energy-to-finish-tasks | C++ | c-by-priyanka1230-u1ck | \n\npublic:\n static bool cmp(vector&v1,vector&v2)\n {\n return (v1[0]-v1[1])>(v2[0]-v2[1]);\n }\n int minimumEffort(vector>& tasks) {\n | priyanka1230 | NORMAL | 2021-08-09T17:13:00.938174+00:00 | 2021-08-09T17:13:00.938219+00:00 | 75 | false | ```\n\n```public:\n static bool cmp(vector<int>&v1,vector<int>&v2)\n {\n return (v1[0]-v1[1])>(v2[0]-v2[1]);\n }\n int minimumEffort(vector<vector<int>>& tasks) {\n sort(tasks.begin(),tasks.end(),cmp);\n int i,sum=0;\n for(i=0;i<tasks.size();i++)\n {\n sum=max(tasks[i][1],tasks[i][0]+sum);\n }\n return sum;\n }\n}; | 1 | 0 | [] | 0 |
minimum-initial-energy-to-finish-tasks | Python3 - greedy, with intuition, algorithm, and proof | python3-greedy-with-intuition-algorithm-i3gzs | Intuition\nFor the last task, we will want to minimize the waste of energy, so we take the task which has the smallest (minimum - actual). If we waste more ener | yunqu | NORMAL | 2021-05-27T02:01:12.772361+00:00 | 2021-05-27T02:35:00.878470+00:00 | 108 | false | **Intuition**\nFor the last task, we will want to minimize the waste of energy, so we take the task which has the smallest (minimum - actual). If we waste more energy, we know it could be done, but it is just not optimal.\n\n**Algorithm**\nContinuing this thinking for all the remaining tasks, we know at each step, we must choose a task that minimizes the waste of energy. Hence we sort the tasks by the waste of energy from smallest to biggest.\n\nThen for each subsequent task `i`, the starting energy to finish it will be one of the 2 following cases:\n\n1. The previous energy up to task `i-1`, plus the current actual consumed energy for task `i`.\n2. The minimum starting energy of task `i`.\n\nWe will take the maximum of the two above cases in each iteration.\n\n**Proof**\nSuppose we have task0 and task1, which has the (actual, minimum) enegery to be (a0, m0) and (a1, m1), respectively. Without loss of generality, we assume m0 - a0 < m1 - a1. In our greedy approach, we will definitely choose task0 as the latter task to finish. \n\nOur greedy approach will require a starting energy of T0 = max(m0 + a1, m1). Now prove by contradiction. Suppose we will choose task1 as the latter one to finish, which achieves lower starting energy. Namely, T1 = max(m1 + a0, m0) < T0. (\\*)\n\n(1) Because m0 - a0 < m1 - a1, we have m1 + a0 > m0 + a1. \n(2) m1 + a0 > m1 because a0 is positive.\n\nDue to (1) and (2), we have m1 + a0 > max(m0 + a1, m1) = T0. \nHence we have T1 = max(m1 + a0, m0) >= m1 + a0 > T0. But T1 > T0 contradicts (\\*). Done\n\n```python\nclass Solution:\n def minimumEffort(self, tasks: List[List[int]]) -> int:\n n = len(tasks)\n t = sorted(tasks, key=lambda v:v[1]-v[0])\n start = t[0][1]\n for i in range(1, n):\n start = max(start + t[i][0], t[i][1])\n return start\n``` | 1 | 0 | [] | 0 |
minimum-initial-energy-to-finish-tasks | C++ sort by difference and explanation in details | c-sort-by-difference-and-explanation-in-oinjp | This is how I came up with the idea that we need to sort the vector by difference. Please let me know if I am not clear enough to you.\n\n1) Supposed we have a | brandonyxf | NORMAL | 2021-05-14T04:20:18.306823+00:00 | 2021-05-14T04:20:18.306858+00:00 | 124 | false | This is how I came up with the idea that we need to sort the vector by difference. Please let me know if I am not clear enough to you.\n\n1) Supposed we have a huge amount of energy which is enough to finish all tasks. There must be some energy left, and we defined it as \'res\'. If we want to finish all the tasks with minimum initial energy, \'res\' has to be minimized.\n\n2) Let\'s think about the final step (step n). For the last task, we need to first satisfied \'minimum\' (requirement of the last tasks) and spend \'actual\' (the energy we spend on the last tasks). Since we want the minimum \'res\', the last tasks should be the ith one such that tasks[i][1] - tasks[i][0] is the smallest among all tasks.\n\n3) Once we found the last tasks, the energy needed for the last step (step n) is fixed. The problem is transferred to find the minimum initial energy for the rest n-1 tasks. We can repeat 2) for these n-1 tasks, which is to find the tasks j such that tasks[j][1] - tasks[j][0] is the smallest among these n-1 tasks.\n\n4) Repeat the process for all tasks. Thus, to find the minimum initial energy, we need to finish the tasks with a larger difference earlier than the one with a smaller difference. That\'s the reason why we need to sort the tasks vector by the difference.\n\n5) Once we sort the vector, we need to satisfied the condition for each task. There are only two conditions for tasks[k]: 1. meet the requirement of tasks[k]; 2. meet the requirement of tasks[k+1] after tasks[k] is finished.\n\nComplexity:\ntime (NlogN)\nspace (NlogN)\n\nHere is my code in c++:\n```\n int minimumEffort(vector<vector<int>>& tasks) {\n sort(tasks.begin(), tasks.end(), [](vector<int>& v1, vector<int>& v2) {return v1[1] + v2[0] > v1[0] + v2[1];});\n int summ = tasks.back()[1];\n \n for (int i = tasks.size() - 2; i >= 0; i--){\n summ = max(tasks[i][0] + summ, tasks[i][1]);\n }\n return summ;\n }\n``` | 1 | 0 | [] | 0 |
minimum-initial-energy-to-finish-tasks | Proof with induction | proof-with-induction-by-infinitetape-uo7t | Assertion: if x as initial energy can finish all tasks in some order, then it must be sufficient to finish all tasks in descending order by (minium \u2013 actua | infinitetape | NORMAL | 2021-05-14T01:43:00.493296+00:00 | 2021-05-14T01:43:00.493344+00:00 | 89 | false | Assertion: if x as initial energy can finish all tasks in some order, then it must be sufficient to finish all tasks in descending order by (minium \u2013 actual).\n\nProof:\nIf there is 1 task, the assertion is obviously true.\n\nIf there are 2 tasks, let\u2019s say we have: [a, a + c1] and [b, b + c2], and c1 >= c2.\nIf we can finish tasks by finishing by order (b, a), then we must have:\n1) x >= b + c2 (b can start)\n2) x - b >= a + c1 (after b, a can start).\nSo we have: x \u2013 b >= a + c1 => x \u2013 a >= b + c1 >= b + c2\nThis means we can complete task a first and then b.\n\nIf there are N tasks and we can finish them in some order that\u2019s different than the above sorting order.\nLet m be the first task not in the above sorting order, that is (D = minimu - actual):\n(i)\tD1 >= D2 >= \u2026 >= Dm-1 < Dm\nSuppose the right position for Dm to be in order is k, that is:\n(ii) D1 >= D2 >= \u2026 >= Dk >= Dm >= Dk+1 >= \u2026 >= Dm-1\nWhat we should prove is that if we can finish tasks in order (i) with initial energy x, we can finish them in order (ii) with x.\nWe can do this by:\n-\tFirst, swapping Dm-1 and Dm in (i), we have (\u2026., Dk, Dk+1, \u2026,Dm-2, Dm, Dm-1). Because Dm > Dm-1, based on the above case where N=2, we must be able to finish taks in this order.\n Note: the preceeding m \u2013 2 tasks are unchanged and are still in order of (D1, D2, \u2026, Dk, Dk+1, \u2026, Dm-2), so if we start with initial energy x, we will have same remaining energy after finishing these m-2 tasks. That is, we are using the same initial energy for processing original (Dm-1, Dm) and the swapped (Dm, Dm-1), therefore can apply the conclusion above with N=2 tasks.\n-\tThen we swap Dm-2 and Dm, we have (\u2026., Dk, Dk+1, \u2026, Dm, Dm-2, Dm-1). And for the same reason we can finish tasks in this order as well.\n-\tKeep swapping, we will have (\u2026, Dk, Dm, Dk+1, \u2026, Dm-2, Dm-1). We can also finish this task order. And this one is sorted by descending of D.\nHereby we proved that the assertion holds when there are N tasks.\n | 1 | 0 | [] | 0 |
minimum-initial-energy-to-finish-tasks | c++ solution of the problem | c-solution-of-the-problem-by-sw2000-ra5u | can anyone explain why i am getting TLE with this code?\n \n\n static bool cmp(vector<int>v1,vector<int>v2){\n \n return ((v1[1]-v1[0])>(v2[1]-v2[ | sw2000 | NORMAL | 2021-05-02T04:06:35.985899+00:00 | 2021-05-28T09:28:12.394898+00:00 | 167 | false | can anyone explain why i am getting TLE with this code?\n \n```\n static bool cmp(vector<int>v1,vector<int>v2){\n \n return ((v1[1]-v1[0])>(v2[1]-v2[0]));\n }\n int minimumEffort(vector<vector<int>>& tasks) {\n \n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n cout.tie(NULL);\n \n \n sort(tasks.begin(),tasks.end(),cmp);\n \n int t=tasks[0][1];\n int c=tasks[0][1]-tasks[0][0];\n for(int i=1;i<tasks.size();i++){\n if(tasks[i][1]>c){\n t+=tasks[i][1]-c;\n c+=tasks[i][1]-c;\n }\n c=c-tasks[i][0];\n }\n \n return t;\n }\n\n``` | 1 | 0 | [] | 2 |
minimum-initial-energy-to-finish-tasks | [Java] Straightforward from the question | java-straightforward-from-the-question-b-4pxc | First, we can think about stratgy to have minimum energy to do all the tasks.\n\nThe first idea come to mind is working on a task with highest minimum value. Ho | heemin32 | NORMAL | 2021-03-20T05:22:12.152900+00:00 | 2021-03-20T05:22:12.152932+00:00 | 126 | false | First, we can think about stratgy to have minimum energy to do all the tasks.\n\nThe first idea come to mind is working on a task with highest minimum value. However, we can easily find the case where this does not work.\nFor example, with [1, 10] and [1, 2], we should work on [1, 2] first to finish them with 11 energy.\n\nThen, should we work on task with lowest minimum value? Then, there is a case where it does not work. [1, 1] and [1, 4].\n\nYou found the pattern here. Maybe we should work first on task with largest gap between actual energy and minimum energy. \nBy working first on a task having the largest gap between actual energey and minimum energy, we can use actual energy of all remaining tasks to meet the minimum energe of the task.\n\n```\nclass Solution {\n\tpublic int minimumEffort(int[][] tasks) {\n\t\tint actual = 0;\n\t\t// Sort task in decreasing order of gap between actual energy and minimum energy\n\t\tArrays.sort(tasks, (a, b) -> ((b[1] - b[0]) - (a[1] - a[0])));\n\t\t\n\t\t// Sum actual energy to work on all tasks.\n\t\tfor (int[] task : tasks) {\n\t\t\tactual += task[0];\n\t\t}\n \n\t\t// We start from this energy\n\t\tint min = actual;\n\t\tfor (int[] task : tasks) {\n\t\t // If remaining energy is lower than minimum energy, we increase that amount.\n\t\t\tif (actual < task[1]) {\n\t\t\t\tmin += task[1] - actual;\n\t\t\t\tactual = task[1];\n\t\t\t} \n\t\t\t// Remove energy we used.\n\t\t\tactual -= task[0];\n\t\t}\n \n\t\treturn min;\n\t}\n}\n```\n\nNow if you see the code above, we are subtracting energy while iterating tasks. \nWhat if we do it in reverse way? \n\nIn this new approach, we need to sort the task in reverse way.\nWe don\'t need to sum the actual energy to start with. Instead, we add actual energy while iterating tasks.\nIf energy we have is not enough for minimum energy requred for a task, we set actual energy to the minimum energy.\n```\nclass Solution {\n public int minimumEffort(int[][] tasks) {\n int actual = 0;\n Arrays.sort(tasks, (a, b) -> ((a[1] - a[0]) - (b[1] - b[0])));\n for (int[] task : tasks) {\n actual += task[0];\n if (actual < task[1]) {\n actual = task[1];\n } \n }\n \n return actual;\n }\n}\n``` | 1 | 0 | [] | 1 |
minimum-initial-energy-to-finish-tasks | Interval scheduling intuition | interval-scheduling-intuition-by-louisqi-d0kp | The problem could be converted into the classic greedy interval scheduling problem. Although this might not be the most optimal solution in terms of runtime, I | louisqin | NORMAL | 2021-03-01T06:53:31.708437+00:00 | 2021-03-01T06:53:31.708475+00:00 | 599 | false | The problem could be converted into the classic greedy interval scheduling problem. Although this might not be the most optimal solution in terms of runtime, I find it very helpful to gain an intuitive understanding of the problem.\n\nHere, we map the concepts in the problem into those in interval scheduling:\n* minimum_i = end time of interval i\n* minimum_i - actual_i = start time of interval i\n* interval_i must not end earlier than minimum_i\n* the problem = when does the last interval end when scheduled greedily?\n\n**The solution as interval scheduling**\n\n```\nclass Solution:\n def minimumEffort(self, tasks: List[List[int]]) -> int: \n intervals = sorted([minimum_i - actual_i, minimum_i] for actual_i, minimum_i in tasks)\n \n for i in range(1, len(intervals)):\n if intervals[i][0] < intervals[i-1][1]:\n inc = intervals[i-1][1] - intervals[i][0]\n intervals[i][0] += inc\n intervals[i][1] += inc\n \n return intervals[-1][1]\n``` | 1 | 0 | [] | 0 |
minimum-initial-energy-to-finish-tasks | C# one line with linq | c-one-line-with-linq-by-user1696y-u1oy | \n public int MinimumEffort(int[][] tasks) {\n return tasks.OrderBy(x => x[1] - x[0]).Aggregate(0, (result, x) => Math.Max(result + x[0], x[1])); | user1696y | NORMAL | 2021-02-14T16:27:21.625007+00:00 | 2021-02-14T16:27:21.625040+00:00 | 67 | false | ```\n public int MinimumEffort(int[][] tasks) {\n return tasks.OrderBy(x => x[1] - x[0]).Aggregate(0, (result, x) => Math.Max(result + x[0], x[1])); \n }\n``` | 1 | 0 | [] | 0 |
minimum-initial-energy-to-finish-tasks | JAVA 90% FAST SIMPLE SOLUTION WITH EXPLANATION WITH TIME AND SPACE | java-90-fast-simple-solution-with-explan-s91z | EXPLANATION:\n required will be minimum if first we choose:\n 1.task with minimum consumption.\n 2.task with maximum initial requirement.\nBUT, both ar | shivam_gupta_ | NORMAL | 2021-02-01T09:01:13.984244+00:00 | 2021-02-01T09:01:13.984281+00:00 | 119 | false | EXPLANATION:\n required will be minimum if first we choose:\n 1.task with minimum consumption.\n 2.task with maximum initial requirement.\nBUT, both are opposite task so we will sort task based on difference b/w initial requirement and consumption. if its same than based on maximum requirement if its also same than based on minimum consumption.\n JAVA CODE IS:\n```\nclass Solution {\n public int minimumEffort(int[][] tasks) {\n\t//SORTING THE TASKS\n Arrays.sort(tasks,(a,b) ->\n (b[1]-b[0])!=(a[1]-a[0])? ((b[1]-b[0])-(a[1]-a[0])) : b[1]!=a[1] ? b[1]-a[1] : b[0]-a[0]);\n int min=0;\n for(int a[] : tasks){\n //System.out.println(a[0]+" "+a[1]);\n min+=a[0];\n }\n int ans=min;\n for(int a[] : tasks){\n if(a[1]>min){\n ans+=(a[1]-min);\n min+=(a[1]-min);\n }\n min-=a[0];\n }\n return ans;\n }\n}\n```\nTime: O(nlogn)+O(n)+O(n)=O(nlogn)\nSpace: O(1) no extra space is used\n***IF THIS IS REALLY HELPFUL FOR YOU PLEASE UPVOTE*** | 1 | 0 | [] | 0 |
minimum-initial-energy-to-finish-tasks | [Python] Binary search solution | python-binary-search-solution-by-modusv-wqu4 | Greedily test an initial energy value and use binary search to span over all the possible initial values.\n\n\nclass Solution:\n def minimumEffort(self, task | modusv | NORMAL | 2020-12-22T14:43:38.622968+00:00 | 2020-12-22T14:44:51.944423+00:00 | 122 | false | Greedily test an initial energy value and use binary search to span over all the possible initial values.\n\n```\nclass Solution:\n def minimumEffort(self, tasks: List[List[int]]) -> int:\n \n def enough(en):\n for actual, minim in tasks:\n if en >= minim:\n en -= actual\n else:\n return False \n return True\n \n tasks.sort(key = lambda x: (x[1] - x[0]), reverse=True)\n\n left = sum([actual for actual, minim in tasks])\n right = sum([minim for actual, minim in tasks])\n \n while left < right:\n mid = left + (right - left) // 2\n if enough(mid):\n right = mid\n else:\n left = mid+1\n \n return left\n``` | 1 | 0 | [] | 0 |
minimum-initial-energy-to-finish-tasks | Java sort by (minimum-actual) | java-sort-by-minimum-actual-by-mayankban-zax6 | ```\nclass Solution {\n public int minimumEffort(int[][] tasks) {\n Arrays.sort(tasks,(a,b)->(b[1]-b[0])-(a[1]-a[0]));\n int energy=0;\n | mayankbansal | NORMAL | 2020-11-30T06:56:16.449702+00:00 | 2020-11-30T06:56:16.449743+00:00 | 97 | false | ```\nclass Solution {\n public int minimumEffort(int[][] tasks) {\n Arrays.sort(tasks,(a,b)->(b[1]-b[0])-(a[1]-a[0]));\n int energy=0;\n int ans=0;\n for(int i=0;i<tasks.length;i++){\n if(energy<tasks[i][1]){\n int req=tasks[i][1]-energy;\n energy+=req;\n ans+=req;\n }\n energy-=tasks[i][0];\n }\n return ans;\n }\n} | 1 | 0 | [] | 0 |
minimum-initial-energy-to-finish-tasks | [C#] O(N) Two Lines | c-on-two-lines-by-a-f-v-ngja | Algorithm\nStep 1) Sum all the actual costs together and add the smallest difference between minimum and actual (this corresponds to summing all actual costs ex | a-f-v | NORMAL | 2020-11-23T00:41:31.266068+00:00 | 2020-11-23T00:43:35.777912+00:00 | 69 | false | # Algorithm\nStep 1) Sum all the actual costs together and add the smallest difference between minimum and actual (this corresponds to summing all actual costs excluding your last choice which needs to use minimum)\nStep 2) Make sure it is not greater than largest minimum\n# Code\n```csharp\npublic class Solution {\npublic int MinimumEffort(int[][] tasks)\n {\n int sum = tasks.Sum(ints => ints[0]) + tasks.Min((ints => ints[1]-ints[0])); \n return Math.Max(sum, tasks.Max((ints => ints[1])));\n }\n}\n```\n\n# Explanation\nDon\'t have a great on at the moment, feel free to maybe discuss and I\'ll update.\nWould involve showing that greedy approach is optimal. Also maybe look at effects of commuting pairs of tasks. | 1 | 0 | ['C#'] | 1 |
minimum-initial-energy-to-finish-tasks | Easy JAVA Solution | O(n logn) | Sorting | easy-java-solution-on-logn-sorting-by-mi-cllk | Easy to understand Java Solution\nSorting on the basis of MAXIMUM Difference between the Minimum And Actual Energy Requirements\n\n\nclass Solution {\n publi | mihir_sood | NORMAL | 2020-11-22T04:32:10.343794+00:00 | 2020-11-22T04:32:10.343839+00:00 | 138 | false | Easy to understand Java Solution\nSorting on the basis of MAXIMUM Difference between the Minimum And Actual Energy Requirements\n\n```\nclass Solution {\n public int minimumEffort(int[][] tasks) {\n int tot=0; // total effort required\n for(int[] t:tasks){\n tot+=t[0];\n }\n int res=tot; // the result to be returned\n int rem=tot; // a temporary variable to keep track of our expenses\n Arrays.sort(tasks, (a,b)->(b[1]-b[0])-(a[1]-a[0]));\n for(int[]t:tasks){\n if(t[1]>rem){\n int val=t[1]-rem;\n res+=val;\n rem+=val;\n }\n rem-=t[0];\n }\n return res;\n }\n}\n``` | 1 | 1 | ['Array', 'Greedy', 'Sorting', 'Java'] | 0 |
minimum-initial-energy-to-finish-tasks | [c++] Binary Search TLE | c-binary-search-tle-by-askvij-weit | I see lots of solution passed using binary serach. I got TLE using binary serach wondering why ?\n\n\nclass Solution {\npublic:\n int minimumEffort(vector< | askvij | NORMAL | 2020-11-22T04:29:55.919522+00:00 | 2020-11-22T06:43:05.455725+00:00 | 346 | false | I see lots of solution passed using binary serach. I got TLE using binary serach wondering why ?\n\n```\nclass Solution {\npublic:\n int minimumEffort(vector<vector<int>>& tasks) {\n long long lo = 0, hi = 0;\n for (auto task : tasks) lo += task[0], hi += task[1];\n sort(tasks.begin(), tasks.end(), [](auto a , auto b) {\n if (a[1] - a[0] != b[1]- b[0]) return a[1] - a[0] > b[1] - b[0];\n return a[1] > b[1];\n \n });\n \n //for (auto task : tasks) cout << task[0]<<":"<<task[1]<<" "; cout <<"\\n";\n auto isValid = [](long long energy, vector<vector<int>> tks) {\n //cout << energy<<":: \\t";\n int mini = tks[0][1], maxi = tks[0][0];\n int idx = 0;\n for (auto task : tks) {\n if (task[1] <= energy) energy -= task[0];\n else \n return false;\n if (tks[0][0] == task[0]) mini = min (mini, task[1]);\n idx++;\n }\n return true;\n };\n while (lo < hi) {\n long long mid = (lo + hi)/2;\n //cout << lo << " "<<mid <<" "<<hi<<"\\t"; \n if (isValid(mid, tasks)) hi = mid;\n else lo = mid + 1;\n //cout << lo << " "<<mid <<" "<<hi<<"\\n"; \n }\n return lo;\n }\n};\n```\n\nHelp will be appericiated. I spend lot of time debugging it but didn\'t find anything usefull | 1 | 0 | ['Binary Tree'] | 3 |
minimum-initial-energy-to-finish-tasks | [Help] Why Binary Search gives TLE ? | help-why-binary-search-gives-tle-by-vrko-36dn | I have code it using binary search.\n\ncomplexity can be O(nlog(1e9)).\nstill it gives TLE. while other users having same approach got it accepted.\nPlease help | vrkorat211 | NORMAL | 2020-11-22T04:28:31.014909+00:00 | 2020-11-22T04:28:31.014939+00:00 | 240 | false | I have code it using binary search.\n\ncomplexity can be O(nlog(1e9)).\nstill it gives TLE. while other users having same approach got it accepted.\nPlease help where i am missing something?\nThanks in advance.\n```\nclass Solution {\npublic:\n int minimumEffort(vector<vector<int>>& a) {\n sort(a.begin(),a.end(),[&](vector<int> p,vector<int> q){\n if(p[1]-p[0] > q[1]-q[0])\n return true;\n return false;\n });\n int n = a.size();\n auto okk = [&](int m){\n for(int i = 0;i<n;i++)\n {\n if(m < a[i][1])\n return false;\n m -= a[i][0];\n }\n return true;\n };\n int l = 1,r = 1e9;\n int s = 0;\n for(auto v:a)\n {\n l = max(l,v[1]);\n s+=v[0];\n }\n l = max(s,l);\n int ans;\n while(l < r)\n {\n int m = (l+r)/2;\n if(okk(m))\n {\n r = m;\n ans = m;\n }\n else\n {\n l = m+1;\n }\n // cout<<l<<" "<<r<<" "<<m<<endl;\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['Binary Tree'] | 1 |
minimum-initial-energy-to-finish-tasks | [C++] Can anyone help me explain this ? Please! | c-can-anyone-help-me-explain-this-please-0obb | \tclass Solution {\n\tpublic:\n\t\tint minimumEffort(vector>& tasks) {\n\t\t\tauto comp = {\n\t\t\t\tint diff1 = abs(a[1] - a[0]);\n\t\t\t\tint diff2 = abs(b[1 | jasperzhou | NORMAL | 2020-11-22T04:15:48.980191+00:00 | 2020-11-22T04:15:48.980230+00:00 | 161 | false | \tclass Solution {\n\tpublic:\n\t\tint minimumEffort(vector<vector<int>>& tasks) {\n\t\t\tauto comp = [](vector<int>& a, vector<int>& b) {\n\t\t\t\tint diff1 = abs(a[1] - a[0]);\n\t\t\t\tint diff2 = abs(b[1] - b[0]);\n\t\t\t\treturn diff1 >= diff2;\n\t\t\t};//when I use this to sort, I got an error, but when I deleted the = sign, it works.\n\t\t\t// I really cannot figure this out\n\t\t\tsort(tasks.begin(), tasks.end(),comp);\n\t\t\tint low = 1;\n\t\t\tint hi = INT_MAX;\n\t\t\twhile(low < hi) {\n\t\t\t\tint mid = low + (hi - low) / 2;\n\t\t\t\tif(check(tasks,mid)) {\n\t\t\t\t\thi = mid;\n\t\t\t\t} else {\n\t\t\t\t\tlow = mid + 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn low;\n\t\t}\n\t\tbool check(vector<vector<int>>& tasks, int val) {\n\t\t\tfor(auto& x:tasks) {\n\t\t\t\tif(val >= x[1]) {\n\t\t\t\t\tval -= x[0];\n\t\t\t\t} else {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn val >= 0;\n\t\t}\n\t}; | 1 | 0 | ['Binary Tree'] | 1 |
minimum-initial-energy-to-finish-tasks | [Java] DFS Permutation TLE | java-dfs-permutation-tle-by-sheepmeow-9rdm | This solution only passes 10/41 testcases. It\'s apparently very slow because it tries to search through permutations of doing tasks in different orders, so tha | sheepmeow | NORMAL | 2020-11-22T04:07:39.552975+00:00 | 2020-11-22T04:07:39.553005+00:00 | 71 | false | This solution only passes 10/41 testcases. It\'s apparently very slow because it tries to search through permutations of doing tasks in different orders, so that gives a runtime of O(n!) where n is number of tasks...\nComments/thoughts on improvement are welcome!\n```java\nclass Solution {\n // dfs, do task i, find min energy for doing rest of the tasks\n // res = min of doing i now for i = 0...n\n // can use dp to save some results\n // pass in required energy for each pass, if not enough at any point, increase\n public int minimumEffort(int[][] tasks) {\n int n = tasks.length, required = 0;\n boolean[] visited = new boolean[n];\n for (int i = 0; i < n; i++) {\n required += tasks[i][0];\n }\n return minHelper(tasks, visited, n, required);\n }\n \n private int minHelper(int[][] tasks, boolean[] visited, int remain, int required) {\n if (remain == 0) {\n return required;\n }\n int res = Integer.MAX_VALUE, n = tasks.length;\n for (int i = 0; i < n; i++) {\n if (visited[i]) {\n continue;\n }\n visited[i] = true;\n if (required < tasks[i][1]) {\n required = tasks[i][1];\n }\n res = Math.min(res, tasks[i][0] + minHelper(tasks, visited, remain - 1, required - tasks[i][0]));\n visited[i] = false;\n }\n return res;\n }\n}\n``` | 1 | 1 | [] | 0 |
minimum-initial-energy-to-finish-tasks | I love python. It makes everything so easy to write | i-love-python-it-makes-everything-so-eas-mp2r | \n0class Solution:\n def minimumEffort(self, tasks: List[List[int]]) -> int:\n ret = 0\n dict1 = {}\n for i in range(0, len(tasks)):\n | waluigi120 | NORMAL | 2020-11-22T04:05:32.629899+00:00 | 2020-11-22T04:05:32.629942+00:00 | 74 | false | ```\n0class Solution:\n def minimumEffort(self, tasks: List[List[int]]) -> int:\n ret = 0\n dict1 = {}\n for i in range(0, len(tasks)):\n dict1[i] = tasks[i][1]-tasks[i][0]\n for k,v in sorted(dict1.items(), key=lambda item: item[1]):\n if tasks[k][0] + ret < tasks[k][1]:\n ret = tasks[k][1]\n else:\n ret = tasks[k][0] + ret\n return ret \n``` | 1 | 0 | [] | 0 |
minimum-initial-energy-to-finish-tasks | Java Code with custom sort and comment | java-code-with-custom-sort-and-comment-b-3a9x | Sort the array with largest minumum-actual for each task, the top priority is the one with largest difference\nThen build up the minimum requirements by iterati | htttth | NORMAL | 2020-11-22T04:04:02.691832+00:00 | 2020-11-22T04:04:02.691874+00:00 | 81 | false | Sort the array with largest minumum-actual for each task, the top priority is the one with largest difference\nThen build up the minimum requirements by iterating the sorted array and add energy if the remaining is not enough for the next minimum\n\n public int minimumEffort(int[][] tasks) {\n \n // Sort the array where with descending (minimum-actual), which is the order we process the tasks\n Arrays.sort(tasks, new Comparator<int[]>(){\n @Override\n public int compare(int[] o1, int[] o2) {\n if(o1[1]-o1[0] < o2[1]-o2[0]) return 1;\n else if( o1[1]-o1[0] == o2[1]-o2[0]) return 0;\n else return -1;\n }\n });\n\n int current = 0;\n int total = 0;\n //considering the minumum requirements of the task\n //current tracks the remaining energy left for the next tasks, need to increas if less than next minimum\n for(int i=0;i<tasks.length;i++){\n int[] node = tasks[i];\n if(i==0){\n total = node[1];\n current = node[1]-node[0];\n }\n else{\n if(current<node[1]){\n total+=node[1]-current;\n current = node[1]-node[0];\n }\n else{\n current -= node[0];\n }\n }\n \n }\n \n return total;\n } | 1 | 0 | [] | 0 |
minimum-initial-energy-to-finish-tasks | Python Binary Search | python-binary-search-by-an8888ha-ukmx | Pick those task first which are trying hard to show off.\nMeans abs(min-actual)\n\n\nclass Solution:\n def isPossible(self, tasks, energy):\n for task | an8888ha | NORMAL | 2020-11-22T04:01:16.263724+00:00 | 2020-11-22T04:01:16.263767+00:00 | 143 | false | Pick those task first which are trying hard to show off.\nMeans abs(min-actual)\n\n```\nclass Solution:\n def isPossible(self, tasks, energy):\n for task in tasks:\n required,show = task\n if energy < show or energy < required:\n return False\n energy -= required\n return True\n \n def minimumEffort(self, tasks: List[List[int]]) -> int:\n tasks.sort(key = lambda x : -abs(x[1]-x[0]))\n left,right = 0,0\n for task in tasks:\n left += task[0]\n right += task[1]\n result = right\n while left <= right:\n mid = (left + right) // 2\n if self.isPossible(tasks,mid):\n result = mid \n right = mid - 1\n else:\n left = mid + 1\n return result\n``` | 1 | 0 | [] | 0 |
minimum-initial-energy-to-finish-tasks | Sorting | Easy Solution | 29ms | Beats 93% | sorting-easy-solution-29ms-beats-93-by-a-5pf5 | Complexity
Time complexity: O(n)
Space complexity: O(1)
Code | arjav2768 | NORMAL | 2025-03-28T15:21:38.730599+00:00 | 2025-03-28T15:21:38.730599+00:00 | 4 | false | # Complexity
- Time complexity: O(n)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(1)
# Code
```cpp []
class Solution {
public:
int minimumEffort(vector<vector<int>>& tasks) {
sort(tasks.begin(),tasks.end(),[](vector<int> &a, vector<int> &b){
return a[1]-a[0] > b[1]-b[0];
});
int currEnergy = 0,ans = 0;
for(auto &task : tasks){
int req = task[0],minReq = task[1];
if(currEnergy < minReq){
ans += minReq - currEnergy;
currEnergy = minReq;
}
currEnergy -= req;
}
return ans;
}
};
``` | 0 | 0 | ['Sorting', 'C++'] | 0 |
minimum-initial-energy-to-finish-tasks | EASY JAVA | easy-java-by-navalbihani15-85ms | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | navalbihani15 | NORMAL | 2025-03-27T10:54:43.460707+00:00 | 2025-03-27T10:54:43.460707+00:00 | 0 | 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
```java []
class Solution {
public int minimumEffort(int[][] tasks) {
HashMap<Integer, Integer> a = new HashMap<>();
for (int i = 0; i < tasks.length; i++) {
a.put(i, tasks[i][1] - tasks[i][0]);
}
List<Integer> ind = new ArrayList<>(a.keySet());
Collections.sort(ind, (i, j) -> a.get(j) - a.get(i));
int energy = 0, curr = 0;
for (int i = 0; i < ind.size(); i++) {
int z = ind.get(i);
int actual = tasks[z][0], minimum = tasks[z][1];
if (curr < minimum) {
energy += (minimum - curr);
curr = minimum;
}
curr -= actual;
}
return energy;
}
}
``` | 0 | 0 | ['Java'] | 0 |
minimum-initial-energy-to-finish-tasks | EASY JAVA | easy-java-by-navalbihani15-z1se | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | navalbihani15 | NORMAL | 2025-03-27T10:54:41.681129+00:00 | 2025-03-27T10:54:41.681129+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
```java []
class Solution {
public int minimumEffort(int[][] tasks) {
HashMap<Integer, Integer> a = new HashMap<>();
for (int i = 0; i < tasks.length; i++) {
a.put(i, tasks[i][1] - tasks[i][0]);
}
List<Integer> ind = new ArrayList<>(a.keySet());
Collections.sort(ind, (i, j) -> a.get(j) - a.get(i));
int energy = 0, curr = 0;
for (int i = 0; i < ind.size(); i++) {
int z = ind.get(i);
int actual = tasks[z][0], minimum = tasks[z][1];
if (curr < minimum) {
energy += (minimum - curr);
curr = minimum;
}
curr -= actual;
}
return energy;
}
}
``` | 0 | 0 | ['Java'] | 0 |
minimum-initial-energy-to-finish-tasks | [easy intuition] [step-by-step explanation] sorting solution | easy-intuition-step-by-step-explanation-wx9v9 | Intuitionsome terminology : process a task = finish a task = finish an elementNow, let think in the direction if we are not given with the term minimumi.
Then, | somil_jain_120 | NORMAL | 2025-02-01T04:28:38.005863+00:00 | 2025-02-01T04:28:38.005863+00:00 | 3 | false | # Intuition
some terminology : process a task = finish a task = finish an element
Now, let think in the direction if we are not given with the term $$\text{minimum}_i$$.
Then, our answer would always be sum of all the $$\operatorname{actual}_i$$.
So, lets start with this answer only, that is, initial energy = sum of all the $$\operatorname{actual}_i$$.
Now, $$\text{minimum}_i$$ wants to enforce a energy threshold over each $$i$$. That is, if I have current energy = 10 (lets say), and element is like [8, 13]. Then, i can finish this element as 10 >= 8, but since minimum threshold = 13 exists, which means i have to increase my energy by 3 (= 13-10) to finish this element.
So, What we can do is initiate our ans with initial energy = sum of all the $$\operatorname{actual}_i$$ and then traverse over each element and whenever we have low in energy (like in above case, current energy = 10 (lets say), and element is like [8, 13]), we will increase our energy by that much amount (here, 3 (= 13-10)). In code, we are storing this in ```toAdd``` variable.
Now, our main work remaining is how to traverse the array, so that, our ```toAdd``` tem is minimum so that our answer is optimal.
Now, Consider tasks = ```[[1,3],[2,4],[10,11],[10,12],[8,9]]```
Lets, sort this array = ```[[1,3],[2,4],[8,9],[10,11],[10,12]]```
Now, first thing comes in mind is to finish the elements with low $$\text{minimum}_i$$.
another thing comes in mind is to finish the elements with high $$\text{minimum}_i$$.
lets do both and compare our approaches.
1. finish the elements with low $$\text{minimum}_i$$.
```initial answer = 1 + 2 + 8 + 10 + 10 = 31```
```toAdd = 0 ```
array = ```[[1,3],[2,4],[8,9],[10,11],[10,12]]```
i=0, 31-1 = 30
i=1, 30-2 = 28
i=2, 28-8 = 20
i=3, 20-10 = 10
i=4, now , 10 <= 12, need to increase energy by 2, hence toAdd += 2, and energy += 2, hence, finally, 12 - 10 = 2.
Hence, our final answer would be initial_energy + toAdd = 31+2 = 33.
But our optimal answer is 32, that is, toAdd = 1;
2. finish the elements with high $$\text{minimum}_i$$.
```initial answer = 1 + 2 + 8 + 10 + 10 = 31```
```toAdd = 0 ```
array = ```[[1,3],[2,4],[8,9],[10,11],[10,12]]```
i=4, 31-10 = 21
i=3, 21-10 = 11
i=2, 11-8 = 3
i=1, now , 3<=4, need to increase energy by 1, hence toAdd += 1, and energy += 1, hence, finally, 4 - 2 = 2.
i=0, now , 2<=3, need to increase energy by 1, hence toAdd += 1, and energy += 1, hence, finally, 3-1 = 2
Hence, our final answer would be initial_energy + toAdd = 31+2 = 33.
But our optimal answer is 32, that is, toAdd = 1;
Now, both the above approaches are not giving optimal answer, that is regular sorting won't work. We need to think in an optimal way.
Now, lets think in way that [$\text{minimum}_i$, $\text{actual}_i$]. Now,
$\text{actual}_i$ is actual energy needed, while $\text{minimum}_i$ is minimum energy needed. We can see that it is always,
$\text{minimum}_i$ >= $\text{actual}_i$,
other wise , array of tasks in not valid. Suppose $\text{actual}_i$ = 7 and $\text{minimum}_i$ = 4, which means minimum energy needed is 4 while energy needed to finish the task is 7. So, if you have current energy = 5, you can finish this task, and hence final energy =5 - 7 = -2, which is not possible.
Now,

think the difference between $\text{minimum}_i$ and $\text{actual}_i$. Now, in which order you want to traverse the array ?
Now, suppose you are at the current energy level ```x```, and $\text{minimum}_i$ is significantly larger than $\text{actual}_i$. In this case, you should always prioritize finishing this element first. Why? Because your current energy level is already higher than $\text{minimum}_i$, allowing you to easily cross this threshold. However, since the actual energy required is much lower, your energy level will decrease only slightly. This minimizes energy consumption, increasing the chances that your remaining energy will be higher for the next element, allowing you to cross further thresholds more effectively.
So, We want to process elements with the highest difference between their actual and minimum energy needed, and so on. But if the difference between some elements are same, then what ? then, we will process element with lower thresholds first, so that, we can finish some elements without increasing our ```toAdd``` variable.
# Approach
<!-- Describe your approach to solving the problem. -->
sort the array of tasks based on the difference between actual and minimum energy needs. If difference is same, we want to process the lowest minimum_i first. In the code, we are doing -tasks[i][1] only for sorting purposes
# Complexity
- Time complexity: ```O(nlogn)```
- Space complexity: ```O(n)```
# Code
```cpp []
class Solution {
public:
int minimumEffort(vector<vector<int>>& tasks) {
int n = tasks.size();
vector<vector<int>> arr(n);
int startEnergy = 0, toAdd = 0;
for (int i = 0; i < n; i++) {
startEnergy += tasks[i][0];
int diff = tasks[i][1] - tasks[i][0];
arr[i] = {diff, -tasks[i][1],
tasks[i][0]}; /// difference, min, actual.
////. 0 , 1, 2
}
int startEnergyCopy = startEnergy;
sort(arr.begin(), arr.end());
for (int i = n - 1; i >= 0; i--) {
if (startEnergy >= -arr[i][1]) {
startEnergy -= arr[i][2];
} else {
int temp = -arr[i][1] - startEnergy;
toAdd += temp;
startEnergy += temp;
startEnergy -= arr[i][2];
}
}
return startEnergyCopy + toAdd;
}
};
``` | 0 | 0 | ['Greedy', 'Sorting', 'C++'] | 0 |
minimum-initial-energy-to-finish-tasks | CPP Sorting + Binary Search | cpp-sorting-binary-search-by-zaid_shaikh-6syl | Complexity
Time complexity:
O(NlogM)
Space complexity:
O(1)
Code | Zaid_Shaikh001 | NORMAL | 2025-01-25T19:51:04.723588+00:00 | 2025-01-25T19:51:04.723588+00:00 | 5 | false |
# Complexity
- Time complexity:
O(NlogM)
- Space complexity:
O(1)
# Code
```cpp []
class Solution {
public:
bool canComplete(long long currentEnergy, vector<vector<int>>& tasks) {
for (auto t : tasks) {
if (currentEnergy >= t[1]) {
currentEnergy -= t[0];
} else {
return false;
}
}
return true;
}
int minimumEffort(vector<vector<int>>& tasks) {
// 1. sort by (minimum - actual) because a greater (minimum - actual)
// value requires a high starting energy but does not consume much
// actual energy hence we might have enough energy to start other tasks
// as well.
// 2. binary search on len(tasks) ..... sum(tasks[1])
sort(tasks.begin(), tasks.end(), [](vector<int>& t1, vector<int>& t2) {
return (t1[1] - t1[0]) > (t2[1] - t2[0]);
});
long long low = tasks.size();
long long high = 1e9;
while (low <= high) {
long long mid = low + (high - low) / 2;
if (canComplete(mid, tasks)) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return low;
}
};
``` | 0 | 0 | ['Array', 'Greedy', 'Sorting', 'C++'] | 0 |
minimum-initial-energy-to-finish-tasks | 1665. Minimum Initial Energy to Finish Tasks | 1665-minimum-initial-energy-to-finish-ta-kgyv | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | G8xd0QPqTy | NORMAL | 2025-01-14T14:41:12.057638+00:00 | 2025-01-14T14:41:12.057638+00:00 | 10 | 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
```python3 []
class Solution:
def minimumEffort(self, tasks: List[List[int]]) -> int:
tasks.sort(key=lambda x: x[1] - x[0], reverse=True)
total_effort = 0
current_energy = 0
for effort, minimum in tasks:
if current_energy < minimum:
total_effort += minimum - current_energy
current_energy = minimum
current_energy -= effort
return total_effort
``` | 0 | 0 | ['Python3'] | 0 |
minimum-initial-energy-to-finish-tasks | DP greedy sort | dp-greedy-sort-by-quinnhindmarsh-52h1 | IntuitionWe want do to the tasks with the least difference between the start and actual cost last.Approach
Sort the array by minimum difference between start an | quinnhindmarsh | NORMAL | 2024-12-24T03:29:34.026424+00:00 | 2024-12-24T03:29:34.026424+00:00 | 7 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
We want do to the tasks with the least difference between the start and actual cost last.
# Approach
<!-- Describe your approach to solving the problem. -->
1. Sort the array by minimum difference between start and actual cost.
2. Determine the minimum cost to start the first task (tasks[0][1])
3. Build this up by using this to find the minimum cost for the next task.
4. Return the minimum cost to start the end task.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
$O(n log n)$
1. itterate over the array O(n)
2. sorting O(n log n)
3. itterate over the array again O(n)
- Space complexity:
$O(n)$
a constant amount of data is being stored for each element O(n)
# Code
```python3 []
class Solution:
def minimumEffort(self, tasks: List[List[int]]) -> int:
# Creates a 3rd element in each inner array which represents the difference between the inital energy and cost
for item in tasks:
item.append(item[1] - item[0])
# Sorts by difference
tasks.sort(key=self.sort_key)
# Making a prefix array of minimum cost to start from the current point
tasks[0].append(tasks[0][1])
for i in range(1, len(tasks)):
# If the start cost of the current task > cumulitive start cost for previous tasks
if tasks[i][1] > tasks[i-1][3]:
tasks[i].append(tasks[i][1])
# If the start cost for this minus the cost to complete < min start cost for previous
if tasks[i][1] - tasks[i][0] < tasks[i-1][3]:
# Min cost to start current = min cost to start previous + cost to complete this
tasks[i][3] = tasks[i-1][3] + tasks[i][0]
else:
# The min cost to start current = min cost to start previous + cost to complete current
tasks[i].append(tasks[i-1][3])
tasks[i][3] += tasks[i][0]
return tasks[-1][3]
def sort_key(self, e):
return e[2]
``` | 0 | 0 | ['Dynamic Programming', 'Greedy', 'Sorting', 'Prefix Sum', 'Python3'] | 0 |
minimum-initial-energy-to-finish-tasks | mathematical proof of greedy | mathematical-proof-of-greedy-by-___arash-keic | Mathematical Proof of greedy
lets assume I have budget=budget
doing (a,b) first and then (c,d) is better or doing (c,d) first and then (a,b). Assuming: d-c> | ___Arash___ | NORMAL | 2024-12-24T00:24:58.550505+00:00 | 2024-12-24T00:24:58.550505+00:00 | 3 | false | # Mathematical Proof of greedy
1. lets assume I have budget=budget
2. doing (a,b) first and then (c,d) is better or doing (c,d) first and then (a,b). Assuming: d-c>=b-a
3. if we prove that doing (c,d) first and then (a,b) is better, we actually proved greedy approach and why we sort and why we start from the one having greatest difference in actual_i and minimum_i
4. doing (c,d) first and then (a,b):
budget-d
budget-d+(d-c)
budget-d+(d-c)-b
budget-d+(d-c)-b+(b-a)
worst_we_get=min(budget-d,budget-b-c)
5. doing (a,b) first and then (c,d):
budget-b
budget-b+(b-a)
budget-b+(b-a)-d
budget-b+(b-a)-d+(d-c)
worst_we_get=min(budget-b,budget-a-d)
6. compare them and prove that
min(budget-d,budget-b-c)>=min(budget-b,budget-a-d)
equivalent to both of following two inequalities being true simultaneously
0>=min(c,b+c-a-d) correct as min(c,b+c-a-d)<=(b-a)-(d-c)
0>=min(d-b,-a) correct as min(d-b,-a)<=-a
# Complexity
- Time complexity:
O(n log n)
# Code
```python []
class Solution(object):
def minimumEffort(self, tasks):
tasks.sort(key=lambda (a,b):a-b)
worst=float('inf')
cur=0
for a,b in tasks:
cur-=b
worst=min(worst,cur)
cur+=b-a
return -worst
``` | 0 | 0 | ['Python'] | 0 |
minimum-initial-energy-to-finish-tasks | Minimum Initial Energy to Finish Tasks Runtime 100% and Memory 90 % | minimum-initial-energy-to-finish-tasks-r-czk5 | Intuition\nThe key insight is that we want to minimize the initial energy required to complete all tasks. Tasks with a high minimum requirement but low actual e | FujMYV1KQS | NORMAL | 2024-12-09T03:28:40.885404+00:00 | 2024-12-09T03:28:40.885429+00:00 | 2 | false | # Intuition\nThe key insight is that we want to minimize the initial energy required to complete all tasks. Tasks with a high minimum requirement but low actual energy consumption should be done first, as they have the biggest impact on our initial energy needs.\n\n# Approach\n1. Sort the tasks based on the difference between minimum required energy and actual energy consumption (minimum - actual) in descending order\n2. Keep track of two variables:\n - `currentEnergy`: represents our current energy level\n - `initialEnergy`: represents the minimum initial energy needed\n3. For each task:\n - If our current energy is less than the minimum required, we need to increase our initial energy\n - After completing each task, reduce our current energy by the actual energy consumed\n\n# Complexity\n- Time complexity: **O(n log n)**\n - The sorting operation takes O(n log n)\n - The loop through tasks takes O(n)\n - Overall complexity is dominated by the sort: O(n log n)\n\n- Space complexity: **O(1)**\n - We only use a constant amount of extra space regardless of input size\n - The sorting is typically done in-place for arrays\n\n# Code Explanation\n```csharp\n// Sort tasks by (minimum - actual) difference in descending order\n// This ensures we handle tasks with highest energy requirements first\nArray.Sort(tasks, (a, b) => (b[1] - b[0]) - (a[1] - a[0]));\n\nforeach (var task in tasks) {\n int actual = task[0]; // Energy consumed by the task\n int minimum = task[1]; // Minimum energy required to start\n \n // If current energy is less than minimum required\n // We need to increase our initial energy\n if (currentEnergy < minimum) {\n initialEnergy += minimum - currentEnergy;\n currentEnergy = minimum;\n }\n \n // After task completion, reduce energy by actual amount used\n currentEnergy -= actual;\n}\n``` | 0 | 0 | ['C#'] | 0 |
minimum-initial-energy-to-finish-tasks | Greedy after Sorting based on the difference !! | greedy-after-sorting-based-on-the-differ-6xff | Approach: \n- We just need to sort the tasks vector based on the difference between the actual & minimum energy required in descending order.\n- Then we can tra | Axnjr | NORMAL | 2024-10-29T11:58:47.229592+00:00 | 2024-10-29T11:58:47.229634+00:00 | 5 | false | # Approach: \n- We just need to sort the `tasks` vector based on the difference between the actual & minimum energy required in descending order.\n- Then we can traverse the sorted array with `startEnergy` & `remEnergy` variables set to `0`.\n- We will keep adding the `diff` required to keep doing tasks. `GREEDY \uD83E\uDD11`\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(NlogN + N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int minimumEffort(vector<vector<int>>& task) {\n sort(task.begin(), task.end(), [](const vector<int>& a, const vector<int>& b) {\n return (a[1] - a[0]) > (b[1] - b[0]);\n });\n\n int startEnergy = 0, remEnergy = 0;\n\n for (const auto& t : task) {\n if (remEnergy < t[1]) {\n int diff = t[1] - remEnergy;\n startEnergy += diff;\n remEnergy += diff;\n }\n remEnergy -= t[0];\n }\n \n return startEnergy;\n }\n};\n``` | 0 | 0 | ['Greedy', 'Sorting', 'C++'] | 0 |
minimum-initial-energy-to-finish-tasks | Custom Sort Greedily | custom-sort-greedily-by-theabbie-o0db | \nfrom functools import cmp_to_key\n\nclass Solution:\n def minimumEffort(self, tasks: List[List[int]]) -> int:\n def cmp(a, b):\n if max(a | theabbie | NORMAL | 2024-10-22T18:53:03.027186+00:00 | 2024-10-22T18:53:03.027209+00:00 | 2 | false | ```\nfrom functools import cmp_to_key\n\nclass Solution:\n def minimumEffort(self, tasks: List[List[int]]) -> int:\n def cmp(a, b):\n if max(a[1], a[0] + max(b[0], b[1])) > max(b[1], b[0] + max(a[0], a[1])):\n return 1\n return -1\n tasks.sort(key = cmp_to_key(cmp))\n res = 0\n used = 0\n for i in range(len(tasks)):\n res = max(res, used + tasks[i][1])\n used += tasks[i][0]\n return res\n``` | 0 | 0 | ['Python'] | 0 |
minimum-initial-energy-to-finish-tasks | Minimum Initial Energy to Finish Tasks | minimum-initial-energy-to-finish-tasks-b-8eqx | Approach\n Describe your approach to solving the problem. \nSort the Tasks by "Difference":\nWe should prioritize tasks that have a larger difference between mi | Ansh1707 | NORMAL | 2024-10-11T04:53:38.741556+00:00 | 2024-10-11T04:53:38.741592+00:00 | 2 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\nSort the Tasks by "Difference":\nWe should prioritize tasks that have a larger difference between minimumi and actuali. This way, we maximize the leftover energy by starting with tasks that are "expensive" in terms of their starting requirement but "cheap" in terms of actual energy consumption.\nSort the tasks by the difference: minimumi - actuali in descending order. This ensures we handle the more restrictive tasks (in terms of energy to start) earlier, leaving more room for the easier tasks later.\n\nSimulate the Execution:\nOnce the tasks are sorted, we calculate the minimum initial energy needed by iterating over the sorted list. For each task, we ensure that we have enough energy to meet its minimumi requirement before subtracting the actuali used to complete the task.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nSorting: Sorting the tasks takes O(nlogn), where n is the number of tasks.\n\nTask iteration: The iteration over the sorted tasks takes O(n). Thus, the overall time complexity is O(nlogn).\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is O(1) for storing the energy values and constants, excluding the input space.\n\n# Code\n```python []\nclass Solution:\n def minimumEffort(self, tasks):\n # Sort tasks by the difference (minimum - actual), in descending order\n tasks.sort(key=lambda x: x[1] - x[0], reverse=True)\n \n total_energy = 0\n current_energy = 0\n \n for actual, minimum in tasks:\n # If current energy is less than the minimum required energy for the task\n if current_energy < minimum:\n # Add the difference to total_energy and current_energy\n total_energy += (minimum - current_energy)\n current_energy = minimum\n \n # After performing the task, reduce current energy by the actual cost\n current_energy -= actual\n \n return total_energy\n\n``` | 0 | 0 | ['Python'] | 0 |
minimum-initial-energy-to-finish-tasks | 1665. Minimum Initial Energy to Finish Tasks.cpp | 1665-minimum-initial-energy-to-finish-ta-xo8n | Code\n\nclass Solution {\npublic: \n static bool cmp(const pair<int,pair<int,int>>&a,const pair<int,pair<int,int>>&b)\n {\n if(a.first==b.first) | 202021ganesh | NORMAL | 2024-10-08T07:26:46.784948+00:00 | 2024-10-08T07:26:46.784972+00:00 | 2 | false | **Code**\n```\nclass Solution {\npublic: \n static bool cmp(const pair<int,pair<int,int>>&a,const pair<int,pair<int,int>>&b)\n {\n if(a.first==b.first)\n {\n return a.second.second>b.second.second;\n }\n else\n return a.first>b.first; \n } \n int minimumEffort(vector<vector<int>>& tasks) \n { \n vector<pair<int,pair<int,int>>>v;\n for(int i=0;i<tasks.size();i++)\n v.push_back({tasks[i][1]-tasks[i][0],{tasks[i][0],tasks[i][1]}}); \n sort(v.begin(),v.end(),cmp); \n int sum=0;\n int n=tasks.size(); \n for(int i=0;i<n;i++)\n sum+=v[i].second.first; \n sum=max(sum,v[0].second.second); \n int temp=sum; \n for(int i=0;i<v.size();i++)\n {\n if(temp>=v[i].second.second)\n {\n temp=temp-v[i].second.first;\n }\n else\n {\n sum+=abs(temp-v[i].second.second);\n temp+=abs(temp-v[i].second.second);\n temp=temp-v[i].second.first;\n }\n } \n return sum; \n }\n};\n``` | 0 | 0 | ['C'] | 0 |
minimum-initial-energy-to-finish-tasks | In C++ | in-c-by-ranjithgopinath-f526 | 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 | RanjithGopinath | NORMAL | 2024-10-06T14:33:06.452221+00:00 | 2024-10-06T14:33:06.452251+00:00 | 0 | 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```cpp []\nclass Solution {\npublic:\n int minimumEffort(vector<vector<int>>& tasks) {\n // Sort the tasks based on the difference between minimum energy and actual energy, in descending order\n sort(tasks.begin(), tasks.end(), [](const vector<int>& a, const vector<int>& b) {\n return (a[1] - a[0]) > (b[1] - b[0]);\n });\n \n int initialEnergy = 0, currentEnergy = 0;\n \n // Iterate through the tasks\n for (auto& task : tasks) {\n int actual = task[0], minimum = task[1];\n \n // If current energy is less than the required minimum energy, we need to add the difference\n if (currentEnergy < minimum) {\n initialEnergy += minimum - currentEnergy;\n currentEnergy = minimum;\n }\n \n // After completing the task, reduce the energy by the actual energy spent\n currentEnergy -= actual;\n }\n \n return initialEnergy;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-initial-energy-to-finish-tasks | 💥 Beats 100% on runtime and memory [EXPLAINED] | beats-100-on-runtime-and-memory-explaine-immb | Intuition\nThe problem revolves around managing energy effectively while completing tasks. Each task requires a minimum energy to start and consumes a certain a | r9n | NORMAL | 2024-10-01T21:31:47.528212+00:00 | 2024-10-01T21:31:47.528245+00:00 | 1 | false | # Intuition\nThe problem revolves around managing energy effectively while completing tasks. Each task requires a minimum energy to start and consumes a certain amount of energy. If your current energy is insufficient for a task, you need to ensure you start with enough energy to complete all tasks without running out.\n\n# Approach\nSort the tasks based on the difference between minimum and actual energy needed, then iterate through them, adjusting the initial energy required if your current energy falls below the minimum needed for each task.\n\n# Complexity\n- Time complexity:\nO(n log n) due to sorting the tasks.\n\n- Space complexity:\nO(n) because sorting can use additional space for temporary storage.\n\n# Code\n```typescript []\n/**\n * @param {number[][]} tasks - A 2D array where each sub-array contains the actual energy spent and the minimum energy required for each task.\n * @return {number} - The minimum initial energy required to finish all tasks.\n */\nfunction minimumEffort(tasks: number[][]): number {\n // Sort tasks primarily by the difference (minimum - actual) in descending order\n tasks.sort((a, b) => (b[1] - b[0]) - (a[1] - a[0]));\n\n let minimumEnergy = 0; // Minimum energy needed to start\n let currentEnergy = 0; // Current energy level after completing tasks\n\n for (const [actual, minimum] of tasks) {\n // If current energy is insufficient for the next task\n if (currentEnergy < minimum) {\n // Calculate how much more energy is needed\n const energyNeeded = minimum - currentEnergy;\n minimumEnergy += energyNeeded; // Increase the minimum energy required\n currentEnergy += energyNeeded; // Simulate starting with that much energy\n }\n // After the task, decrease the current energy\n currentEnergy -= actual; \n }\n\n return minimumEnergy; // Return the total minimum energy needed\n}\n\n// Example test cases\nconsole.log(minimumEffort([[1, 2], [2, 4], [4, 8]])); // Expected output: 8\nconsole.log(minimumEffort([[1, 3], [2, 4], [10, 11], [10, 12], [8, 9]])); // Expected output: 32\nconsole.log(minimumEffort([[1, 7], [2, 8], [3, 9], [4, 10], [5, 11], [6, 12]])); // Expected output: 27\n\n``` | 0 | 0 | ['TypeScript'] | 0 |
minimum-initial-energy-to-finish-tasks | Beats 99% CPP Solution Easy to Understand | beats-99-cpp-solution-easy-to-understand-xuln | 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 | kingsenior | NORMAL | 2024-09-17T05:57:42.243863+00:00 | 2024-09-17T05:57:42.243892+00:00 | 3 | 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```cpp []\nclass Solution {\npublic:\n int minimumEffort(vector<vector<int>>& tasks) {\n vector<pair<int,int>> a;\n for(int i=0;i<tasks.size();i++){\n a.push_back({tasks[i][1]-tasks[i][0],i});\n }\n sort(a.begin(),a.end());\n reverse(a.begin(),a.end());\n int ans = 0,tot = 0;;\n for(int i=0;i<a.size();i++){\n int j = a[i].second;\n int consume = tasks[j][0];\n int need = tasks[j][1];\n if(ans<need){\n tot+=(need-ans);\n ans = need;\n }\n ans-=consume;\n }\n return tot;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-initial-energy-to-finish-tasks | Sort Only, simple Solution, beats 95% | sort-only-simple-solution-beats-95-by-ts-5gbj | Intuition\nWe sort the tasks by the differential between actual and minimum. Then the smallest differential will be the latest tasks we finished. Because we wan | tsengh2 | NORMAL | 2024-07-18T23:59:56.091792+00:00 | 2024-07-18T23:59:56.091818+00:00 | 35 | false | # Intuition\nWe sort the tasks by the differential between actual and minimum. Then the smallest differential will be the latest tasks we finished. Because we want the remain energy as fewer as better. Then we just choose to add up the actual energy if the remain energy is able to start the task or set the energy to the minimum to start the task in each step.\n\n# Complexity\n- Time complexity: O(nlogn)\n\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution:\n def minimumEffort(self, tasks: List[List[int]]) -> int:\n \n tasks.sort(key = lambda x: x[1]-x[0])\n energy = 0\n for task in tasks:\n if energy + task[0] >= task[1]:\n energy += task[0]\n else:\n energy = task[1]\n\n return energy\n\n``` | 0 | 0 | ['Python3'] | 0 |
minimum-initial-energy-to-finish-tasks | C++ Greedy Algorithm with Custom Sorting | c-greedy-algorithm-with-custom-sorting-b-2emy | Intuition\nThe key insight is to prioritize tasks that have a larger gap between their minimum required effort and actual cost. By tackling these "high-demand" | orel12 | NORMAL | 2024-07-10T19:26:07.205594+00:00 | 2024-07-10T19:26:07.205619+00:00 | 8 | false | # Intuition\nThe key insight is to prioritize tasks that have a larger gap between their minimum required effort and actual cost. By tackling these "high-demand" tasks first, we can minimize the initial energy required.\n\n# Approach\n1. Sort tasks: Arrange tasks in descending order based on the difference between minimum required effort and actual cost.\n2. Iterate and accumulate:\n - For each task, check if current energy is sufficient.\n - If not, increase the total energy required.\n - Update current energy after each task.\n\n- The algorithm ensures we always have just enough energy to start each task.\n\n- By processing tasks with larger differences first, we minimize the chance of unnecessarily increasing our initial energy.\n\n- This greedy approach leads to the optimal solution for the minimum initial energy required.\n\n- The sorting is crucial and must be in decreasing order of the difference (minimum required - actual cost). Sorting in increasing order would lead to an incorrect result.\n\n- For tasks with the same difference, their relative order doesn\'t affect the final result.\n\n- The `result` variable represents the total minimum initial energy needed, while `current` keeps track of the energy level after each task.\n\n# Complexity\n- Time complexity: $$O(n log n)$$\nThe sorting step dominates the time complexity, where n is the number of tasks.\n\n- Space complexity: $$O(1)$$ or $$O(log n)$$\n$$O(1)$$ additional space is used for variables. The space complexity of the sorting algorithm (typically $$O(log n)$$ for most built-in sorts) may need to be considered depending on the implementation.\n\n# Code\n```\nclass Solution {\npublic:\n int minimumEffort(vector<vector<int>>& tasks) {\n auto comparator = [](const vector<int>& a, const vector<int>& b) {\n int diffA = a[1] - a[0];\n int diffB = b[1] - b[0];\n return diffA > diffB;\n };\n sort(tasks.begin(), tasks.end(), comparator);\n int result = 0;\n int current = 0;\n \n for (const auto& task : tasks) {\n if (current < task[1]) {\n result += task[1] - current;\n current = task[1];\n }\n current -= task[0];\n }\n \n return result;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-initial-energy-to-finish-tasks | Greedy approach. Sorted using comparator.C++ | greedy-approach-sorted-using-comparatorc-c5w1 | Intuition\nThe more you energyyou save from the current task can be used later on.Simple greedy approach\n\n# Approach\nUsed a comparator to sort the tasks vect | anubhavkrishna | NORMAL | 2024-07-09T21:07:38.471877+00:00 | 2024-07-09T21:07:38.471902+00:00 | 4 | false | # Intuition\nThe more you energyyou save from the current task can be used later on.Simple greedy approach\n\n# Approach\nUsed a comparator to sort the tasks vector according to the differnce of mininum and actual energy required\n\n# Complexity\n- Time complexity:\nO(nlogn)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\nstatic bool cmp(vector<int>&a,vector<int>&b){\n return (a[1]-a[0])>(b[1]-b[0]);\n}\n int minimumEffort(vector<vector<int>>& tasks) {\n sort(tasks.begin(),tasks.end(),cmp);\n int initial=0,ans=0;\n for(int i=0;i<tasks.size();i++){\n if(tasks[i][1]>initial){\n ans+=tasks[i][1]-initial;\n initial=tasks[i][1];\n }\n initial-=tasks[i][0];\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['Greedy', 'Sorting', 'C++'] | 0 |
minimum-initial-energy-to-finish-tasks | Easy C++ Solution|| Sorting || Binary search | easy-c-solution-sorting-binary-search-by-j7n7 | 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 | ak3177590 | NORMAL | 2024-06-05T17:43:47.212840+00:00 | 2024-06-05T17:43:47.212872+00:00 | 5 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minimumEffort(vector<vector<int>>& tasks) {\n int n=tasks.size();\n\n vector<pair<int,int>>v(n);\n\n for(int i=0;i<n;i++)\n {\n v[i]={tasks[i][0],tasks[i][1]};\n }\n auto cmp=[&](pair<int,int>&p1,pair<int,int>&p2)\n {\n if(p1.second-p1.first !=p2.second-p2.first)\n return p1.second-p1.first > p2.second-p2.first;\n else \n return (double)p1.second/(double)p1.first < (double)p2.second/(double)p2.first;\n };\n sort(v.begin(),v.end(),cmp);\n\n auto find_ans=[&](int x)\n {\n for(int i=0;i<n;i++)\n {\n if(x>=v[i].second)\n x=x-v[i].first;\n else\n return false;\n } \n return true;\n };\n \n int l=1,h=INT_MAX,ans=INT_MAX;\n\n while(l<=h)\n {\n int mid=l+(h-l)/2;\n if(find_ans(mid))\n {\n ans=min(ans,mid);\n h=mid-1;\n }\n else\n l=mid+1;\n }\n return ans;\n\n\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
minimum-initial-energy-to-finish-tasks | Solution Minimum Initial Energy to Finish Tasks | solution-minimum-initial-energy-to-finis-k70x | 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 | Suyono-Sukorame | NORMAL | 2024-05-31T01:43:18.545716+00:00 | 2024-05-31T01:43:18.545733+00:00 | 0 | 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 function minimumEffort($tasks) {\n $ans = 0;\n $energy_left = 0;\n\n usort($tasks, function($a, $b) {\n return ($b[1] - $b[0]) - ($a[1] - $a[0]);\n });\n\n foreach ($tasks as $task) {\n $actual = $task[0];\n $minimum = $task[1];\n\n if ($energy_left < $minimum) {\n $ans += $minimum - $energy_left;\n $energy_left = $minimum - $actual;\n } else {\n $energy_left -= $actual;\n }\n }\n\n return $ans;\n }\n}\n\n``` | 0 | 0 | ['PHP'] | 0 |
minimum-initial-energy-to-finish-tasks | GREEDY || Custom Sorting || Explained | greedy-custom-sorting-explained-by-rasto-j00l | Complexity\n- Time complexity: O(n*log(n)) \n\n- Space complexity: O(1) \n\n# Code\n\nclass Solution {\npublic:\n int minimumEffort(vector<vector<int>>& task | coder_rastogi_21 | NORMAL | 2024-04-20T18:40:15.839168+00:00 | 2024-04-20T18:40:15.839195+00:00 | 4 | false | # Complexity\n- Time complexity: $$O(n*log(n))$$ \n\n- Space complexity: $$O(1)$$ \n\n# Code\n```\nclass Solution {\npublic:\n int minimumEffort(vector<vector<int>>& tasks) {\n //sort in decsending order of difference between minimum and actual energy\n sort(tasks.begin(),tasks.end(), [](vector<int>& a, vector<int>& b) {\n return a[1]-a[0] > b[1]-b[0];\n });\n\n int ans = 0;\n for(auto it : tasks) {\n ans += it[0]; //minimum energy needed is the sum of actual energy of all tasks\n }\n\n int curr = ans;\n for(auto it : tasks) {\n if(curr < it[1]) { //if current energy if lesser than the minimum energy for this task\n ans += (it[1]-curr); //increment initial energy by the difference\n curr = it[1]; //increment current energy to become equal to minimum required energy\n }\n curr -= it[0]; //decrement current energy by the amount needed to perform current task\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['Greedy', 'Sorting', 'C++'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.