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
partition-array-such-that-maximum-difference-is-k
Brute force to optimized | C++
brute-force-to-optimized-c-by-tusharbhar-8v4w
Brute force (TLE)\nTime complexity: worst case - O(n ^ 2)\n\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n sort(nums.be
TusharBhart
NORMAL
2022-07-08T06:55:36.503639+00:00
2022-07-08T06:55:36.503681+00:00
38
false
# Brute force (TLE)\n*Time complexity: worst case - O(n ^ 2)*\n```\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n sort(nums.begin(), nums.end());\n \n int i = 0, j = nums.size() - 1, ans = 0;\n \n while(i < nums.size()) {\n if(nums[j] - nums[i] <= k) ans++, i = j + 1, j = nums.size() - 1;\n else j--;\n }\n \n return ans;\n }\n};\n```\n\n# Optimized\n```\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n sort(nums.begin(), nums.end());\n \n int mn = INT_MAX, mx = INT_MIN, ans = 1;\n for(int i : nums) {\n mn = min(mn, i);\n mx = max(mx, i);\n \n if(mx - mn > k) ans++, mn = mx = i;\n }\n \n return ans;\n }\n};\n```
1
0
['Two Pointers', 'C', 'Sorting']
0
partition-array-such-that-maximum-difference-is-k
JAVA || SORT || BINARY SEARCH || EASY TO UNDERSTAND
java-sort-binary-search-easy-to-understa-sc64
\nclass Solution {\n public int partitionArray(int[] nums, int k) \n {\n Arrays.sort(nums);\n \n int ans=0;\n int i=0;\n
29nidhishah
NORMAL
2022-06-26T16:33:09.740753+00:00
2022-06-26T16:33:09.740802+00:00
44
false
```\nclass Solution {\n public int partitionArray(int[] nums, int k) \n {\n Arrays.sort(nums);\n \n int ans=0;\n int i=0;\n \n while(i<nums.length)\n {\n int curr=nums[i];\n ans++; \n int pos=binarySearch(nums,i,nums[i]+k+1);\n i=pos;\n }\n \n return ans;\n }\n \n public int binarySearch(int nums[],int start,int target)\n {\n int n=nums.length;\n int end=n-1;int ans=n;\n \n while(start<=end)\n {\n int mid=start+(end-start)/2;\n \n if(nums[mid]>=target)\n {\n ans=mid;\n end=mid-1;\n }\n \n else\n start=mid+1;\n }\n \n return ans;\n }\n}\n```
1
0
['Sorting', 'Binary Tree', 'Java']
0
partition-array-such-that-maximum-difference-is-k
java easy to understand O(nlogn) || sorting || beginner friendly || simple approach
java-easy-to-understand-onlogn-sorting-b-16ea
class Solution {\n public int partitionArray(int[] nums, int k) {\n Arrays.sort(nums);\n int start = 0;\n int count=1;\n for(int
Nachiket_
NORMAL
2022-06-20T08:26:51.837905+00:00
2022-06-20T08:26:51.837943+00:00
82
false
class Solution {\n public int partitionArray(int[] nums, int k) {\n Arrays.sort(nums);\n int start = 0;\n int count=1;\n for(int i=1;i<nums.length;i++){\n if((nums[i]-nums[start])>k){\n start = i;\n count++;\n }\n }\n return count;\n }\n}\n\n// Note :- Please upvote if you find it helpful ... Thank you ..!
1
0
['Greedy', 'Sorting', 'Java']
0
partition-array-such-that-maximum-difference-is-k
Java - sort and compare
java-sort-and-compare-by-rohitdhiman0202-9a9f
\nclass Solution {\n public int partitionArray(int[] nums, int k) \n {\n Arrays.sort(nums);\n \n int i =1;\n int prev_val = nu
rohitdhiman0202
NORMAL
2022-06-18T11:17:50.976393+00:00
2022-06-18T11:17:50.976426+00:00
66
false
```\nclass Solution {\n public int partitionArray(int[] nums, int k) \n {\n Arrays.sort(nums);\n \n int i =1;\n int prev_val = nums[0];\n int result =1;\n \n while(i < nums.length)\n {\n if(nums[i] - prev_val > k)\n {\n result++;\n prev_val = nums[i];\n }\n i++;\n }\n \n return result;\n }\n}\n```
1
0
['Sorting', 'Java']
0
partition-array-such-that-maximum-difference-is-k
C++ Simple Soution using Sorting
c-simple-soution-using-sorting-by-moriar-hnnc
\nint partitionArray(vector<int>& nums, int k) {\n \n sort(nums.begin(),nums.end());\n \n int res = 0 , i = 0 , j = 0 , n = nums.siz
moriarty12
NORMAL
2022-06-17T10:26:13.928427+00:00
2022-06-17T10:26:13.928497+00:00
86
false
```\nint partitionArray(vector<int>& nums, int k) {\n \n sort(nums.begin(),nums.end());\n \n int res = 0 , i = 0 , j = 0 , n = nums.size();\n \n while(j<n){\n if(nums[j]-nums[i] > k){ \n res++;\n i = j; \n }\n j++;\n }\n ++res;\n \n return res;\n }\n```
1
0
['C', 'Sorting', 'C++']
0
partition-array-such-that-maximum-difference-is-k
C++ || 6 Lines || Sort + 2 Pointer |Easy to Understand
c-6-lines-sort-2-pointer-easy-to-underst-vfz7
\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n sort(nums.begin(),nums.end());\n int cnt = 1,low = 0,i=0;\n\t\t/
jayprakashray
NORMAL
2022-06-12T05:29:37.063377+00:00
2022-06-12T05:29:37.063411+00:00
38
false
```\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n sort(nums.begin(),nums.end());\n int cnt = 1,low = 0,i=0;\n\t\t//low points to min element and i points to max \n\t\t//whenever their difference exceeds k we update low index and increment counter\n while(i<nums.size())\n {\n if(nums[i]-nums[low] <= k) i++;\n else low = i,cnt++;\n }\n return cnt; \n }\n};\n```
1
0
[]
0
partition-array-such-that-maximum-difference-is-k
O(N) solution C++ (88ms beats 100%) and Java (11ms beats 99.73%)
on-solution-c-88ms-beats-100-and-java-11-v5zj
C++:\n\nconst int ZERO = []() {\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr);\n return 0;\n}();\n\nclass Solution {\npublic:\n bool a[1000
Alvanerle
NORMAL
2022-06-11T18:15:07.734307+00:00
2022-06-12T09:09:37.924961+00:00
85
false
C++:\n```\nconst int ZERO = []() {\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr);\n return 0;\n}();\n\nclass Solution {\npublic:\n bool a[100005];\n \n int partitionArray(vector<int>& nums, int k) {\n int mx = -1;\n for(int num: nums){\n a[num] = 1;\n mx = max(num, mx);\n }\n \n int ans = 0;\n int l = 0;\n while(l <= mx){\n while(l <= mx && !a[l]) l++;\n l += k + 1;\n while(l <= mx && !a[l]) l++;\n ans++;\n }\n \n return ans;\n }\n};\n```\n\n\nJava:\n```\nclass Solution {\n boolean a[] = new boolean[100004];\n \n public int partitionArray(int[] nums, int k) {\n int mx = -1;\n for(int num: nums){\n a[num] = true;\n mx = Math.max(num, mx);\n }\n \n int ans = 0;\n int l = 0;\n while(l <= mx){\n while(l <= mx && !a[l]) l++;\n l += k + 1;\n while(l <= mx && !a[l]) l++;\n ans++;\n }\n \n return ans;\n }\n}\n\n```
1
0
[]
0
partition-array-such-that-maximum-difference-is-k
scala solution.
scala-solution-by-lyk4411-cv77
\n\n def partitionArray(nums: Array[Int], k: Int): Int = {\n nums.sorted.foldLeft((1, nums.min))((acc, cur) =>{\n cur - acc._2 > k match {\n cas
lyk4411
NORMAL
2022-06-11T08:13:00.819270+00:00
2022-06-11T08:13:38.474979+00:00
40
false
```\n\n def partitionArray(nums: Array[Int], k: Int): Int = {\n nums.sorted.foldLeft((1, nums.min))((acc, cur) =>{\n cur - acc._2 > k match {\n case true => (acc._1 + 1, cur)\n case _ => acc\n }\n })._1\n }\n```
1
0
['Scala']
1
partition-array-such-that-maximum-difference-is-k
2 pointers C++
2-pointers-c-by-its_dark-cliz
class Solution {\npublic:\n\n int partitionArray(vector& nums, int k) {\n sort(nums.begin(),nums.end());\n int i=0,j=0,ans=0;\n while(i<
its_Dark_
NORMAL
2022-06-08T08:33:54.162348+00:00
2022-06-08T08:33:54.162393+00:00
67
false
class Solution {\npublic:\n\n int partitionArray(vector<int>& nums, int k) {\n sort(nums.begin(),nums.end());\n int i=0,j=0,ans=0;\n while(i<nums.size()&&j<nums.size()){\n if(nums[j]-nums[i]<=k)j++;\n else {\n i=j;\n ans++;\n }\n }\n return ans+1;\n }\n};
1
0
[]
0
partition-array-such-that-maximum-difference-is-k
[c++]
c-by-svik510-isvq
\tPartition Array Such That Maximum Difference Is K\nclass Solution {\npublic:\n \n int i=0,j=i+1,count=1;\n int length=nums.size();\n
svik510
NORMAL
2022-06-07T16:36:40.109036+00:00
2022-06-07T16:36:40.109084+00:00
47
false
\tPartition Array Such That Maximum Difference Is K\nclass Solution {\npublic:\n \n int i=0,j=i+1,count=1;\n int length=nums.size();\n sort(nums.begin(),nums.end());\n while(j<length)\n {\n if(nums[j]-nums[i]>k)\n {\n count++;\n i=j;\n }\n j++;\n }\n return count;\n }\n};
1
0
['Two Pointers']
0
partition-array-such-that-maximum-difference-is-k
Queue & Sorting Approach in Partition Array
queue-sorting-approach-in-partition-arra-prys
Priority Queue TC:- O(n log n)\n\nclass Solution {\n public int partitionArray(int[] nums, int k) {\n return usePriorityQueue(nums, k);\n }\n \
batman005
NORMAL
2022-06-06T03:46:36.434659+00:00
2022-06-06T03:46:36.434708+00:00
54
false
Priority Queue TC:- O(n log n)\n```\nclass Solution {\n public int partitionArray(int[] nums, int k) {\n return usePriorityQueue(nums, k);\n }\n \n public int usePriorityQueue(int[] nums, int k) {\n PriorityQueue<Integer> p = new PriorityQueue<>();\n for(int num : nums){\n p.offer(num);\n }\n int ans = 0;\n while(!p.isEmpty()){\n ans++;\n int val = p.poll();\n while(!p.isEmpty() && p.peek() - val <= k){\n p.poll();\n }\n }\n return ans ; \n }\n}\n```\nvia Sorting \n```\nclass Solution {\n public int partitionArray(int[] nums, int k) {\n Arrays.sort(nums);\n \n int ans=1,j=0;\n for(int i=1;i<nums.length;i++)\n {\n \n if(nums[i]-nums[j]>k)\n {\n ans++;\n j=i;\n }\n else\n {\n continue;\n }\n \n }\n return ans;\n }\n}\n```\n\nTime complexity = O(n log n)
1
0
['Heap (Priority Queue)', 'Java']
0
partition-array-such-that-maximum-difference-is-k
Python
python-by-hong_zhao-pk2e
python\n nums.sort()\n left = res = 0\n for right in range(len(nums)):\n if nums[right] - nums[left] > k:\n res +
hong_zhao
NORMAL
2022-06-06T01:20:36.957626+00:00
2022-06-06T01:20:36.957660+00:00
55
false
```python\n nums.sort()\n left = res = 0\n for right in range(len(nums)):\n if nums[right] - nums[left] > k:\n res += 1\n left = right\n return res + 1\n```
1
0
['Python']
0
partition-array-such-that-maximum-difference-is-k
JavaScript - 100% Simple & Fastest O(nlogn)
javascript-100-simple-fastest-onlogn-by-t89d7
\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nvar partitionArray = function(nums, k) {\n nums.sort((a, b) => a- b)\n l
Asiful_Islam_Sakib
NORMAL
2022-06-05T15:10:46.787438+00:00
2022-06-07T16:08:32.643497+00:00
66
false
```\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nvar partitionArray = function(nums, k) {\n nums.sort((a, b) => a- b)\n let start = nums[0]\n let count = 0\n for(let i = 1; i < nums.length; i++){\n if(nums[i] - start > k){\n count++\n start = nums[i]\n }\n }\n return count+1\n};\n```
1
1
['Sorting', 'JavaScript']
2
partition-array-such-that-maximum-difference-is-k
java solution by sorting the array
java-solution-by-sorting-the-array-by-ra-8k8b
\nclass Solution {\n public int partitionArray(int[] nums, int k) {\n Arrays.sort(nums);\n int partition=0;\n int start=0;\n for(
Rakesh_Sharma_4
NORMAL
2022-06-05T14:15:50.851705+00:00
2022-06-05T14:15:50.851749+00:00
30
false
```\nclass Solution {\n public int partitionArray(int[] nums, int k) {\n Arrays.sort(nums);\n int partition=0;\n int start=0;\n for(int i=0;i<nums.length;++i)\n {\n if(nums[i]-nums[start]<=k)\n {\n if(i==nums.length-1)\n {\n ++partition;\n }\n }\n else\n {\n start=i;\n ++partition;\n --i;\n }\n }\n return partition;\n }\n}\n```
1
0
['Java']
0
partition-array-such-that-maximum-difference-is-k
C++ | Sorting | Greedy
c-sorting-greedy-by-i_love_dua_lipa-xh1h
Approach :\nIn problem statement, it states that min and max of every subsequence should have difference of at most k. First thing that comes to mind is to coll
coder_with_dimples
NORMAL
2022-06-05T12:53:08.419026+00:00
2022-06-05T12:53:08.419071+00:00
43
false
**Approach** :\nIn problem statement, it states that min and max of every subsequence should have difference of at most k. First thing that comes to mind is to collect all elements that are in each other\'s vicinity. Since here vicinity is matter of difference, best way to collect these elements is sorting. \n\nNow, for minimizing number of subsequences, we\'ll try to make each subsequence as long as possible. Therefore, we\'ll keep on picking up elements as long as difference is at most k. By this way, we are keeping bounds of each subsequence as tight as possible so that next subsequence to be added won\'t get affected with this.\n\n**Code** :\n```\nint partitionArray(vector<int>& nums, int k) {\n int ans = 1;\n int n = nums.size();\n sort(nums.begin(),nums.end());\n int min_num = nums[0];\n for(int i = 1; i < n; i++)\n {\n if(nums[i] - min_num > k)\n {\n ans++;\n min_num = nums[i];\n }\n }\n return ans;\n }\n```
1
0
['Two Pointers', 'C', 'Sorting']
0
partition-array-such-that-maximum-difference-is-k
C++ || Sorting || Binary Search
c-sorting-binary-search-by-arceus55-xhj1
```\nint binarySearch(int low,int high,vector&nums, int k,int left){\n int ans;\n while(low<=high){\n int mid = (low+high)/2;\n
arceus55
NORMAL
2022-06-05T11:55:39.537478+00:00
2022-06-05T11:56:41.695511+00:00
24
false
```\nint binarySearch(int low,int high,vector<int>&nums, int k,int left){\n int ans;\n while(low<=high){\n int mid = (low+high)/2;\n if(nums[mid]-left<=k){\n ans = mid;\n low=mid+1;\n }\n else{\n high=mid-1;\n }\n }\n return ans;\n }\n int partitionArray(vector<int>& nums, int k) {\n int left=0, right = nums.size()-1;\n sort(nums.begin(),nums.end());\n int count=1;\n while(left<=right){\n if(nums[right]-nums[left]<=k){\n break;\n }\n else{\n int idx = binarySearch(left,right,nums,k,nums[left]);\n count++;\n left=idx+1;\n }\n }\n return count;\n }
1
0
[]
0
partition-array-such-that-maximum-difference-is-k
Easy java solution
easy-java-solution-by-nisthaagarwal-ljg1
\nclass Solution {\n public int partitionArray(int[] nums, int k) {\n if(nums== null || nums.length==0) return 0;\n Arrays.sort(nums);\n
nisthaagarwal
NORMAL
2022-06-05T11:54:08.632326+00:00
2022-06-05T11:54:08.632371+00:00
38
false
```\nclass Solution {\n public int partitionArray(int[] nums, int k) {\n if(nums== null || nums.length==0) return 0;\n Arrays.sort(nums);\n int count=1;\n int min= Integer.MAX_VALUE;\n int max= Integer.MIN_VALUE;\n for(int val: nums){\n min= Math.min(val, min);\n max= Math.max(val, max);\n if(max-min> k){\n count++;\n min= max;\n }\n }\n return count;\n }\n}\n```
1
0
['Java']
0
partition-array-such-that-maximum-difference-is-k
✅. | C++ | Faster than 100% | Easy - Understanding
c-faster-than-100-easy-understanding-by-45t8r
As they asked for only number of subsequences, we should\'nt worry about the order of the elements, thus we can sort the nums array.\n\nnow we take 2 variables,
starkster
NORMAL
2022-06-05T08:44:29.065259+00:00
2022-06-05T08:44:29.065297+00:00
28
false
**As they asked for only number of subsequences, we should\'nt worry about the order of the elements, thus we can sort the nums array.**\n\nnow we take 2 variables, start and next, initially both are set to 0\nnow we loop until start < n, else it\'ll be out of bounds\n\nwe keep on increasing the next pointer, if \n1. it is less than n\n2. nums[next] - nums[start] <= k\n\nonce it fails the condition, i.e the start element and the last element (next) difference crossed k, we break out and increment the count of ans.\n\n***we dont consider the last element (next) as it didnt meet the condition, and now we set the start to last element (next) as we start a new subsequnce.***\n\n```\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n int ans = 0;\n int n = nums.size();\n sort(nums.begin(), nums.end());\n int start = 0;\n int next = 0;\n while(start < n){\n while(next < n and nums[next] - nums[start] <= k){\n next++;\n }\n ans++;\n start = next;\n }\n return ans;\n }\n};\n```
1
0
['C', 'Sorting']
1
partition-array-such-that-maximum-difference-is-k
O(N)||C++||SORT||SELECT||EASY UNDERSTANDING||FULL EXPLAINED
oncsortselecteasy-understandingfull-expl-w92u
Just sort the given array and keep track of the minimum and maximum element. When the minimum element changes, you make an extra subsequence. The minimum elemen
adbnemesis
NORMAL
2022-06-05T08:07:05.051484+00:00
2022-06-05T08:07:05.051523+00:00
37
false
Just sort the given array and keep track of the minimum and maximum element. When the minimum element changes, you make an extra subsequence. The minimum element is changed the moment when nums[i]-min > k\n\n```\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n sort(begin(nums),end(nums));\n int n = nums.size();\n int ans = 0;\n int cmin = nums[0];\n for(int i = 1;i<n;i++){\n if(nums[i]-cmin > k){\n cmin = nums[i];\n \n ans++;\n }\n }\n return ans+1;\n }\n};\n```
1
0
['C', 'Sorting']
0
partition-array-such-that-maximum-difference-is-k
Simple 5 line code || c++
simple-5-line-code-c-by-jainss-1i4l
\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n sort(nums.begin(),nums.end());\n int ans=0,j=0;\n for(int
jainss
NORMAL
2022-06-05T08:04:46.098096+00:00
2022-06-05T08:04:46.098141+00:00
31
false
```\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n sort(nums.begin(),nums.end());\n int ans=0,j=0;\n for(int i=1;i<nums.size();i++){\n if(nums[i]-nums[j]>k){\n ans++;\n j=i;\n }\n }\n return ans+1;\n }\n};\n```
1
0
['C', 'Sorting']
0
partition-array-such-that-maximum-difference-is-k
C++ Greedy
c-greedy-by-arrxy-7b1d
We need to find subsequence so we can sort the array and use sliding window to keep check for max - min, whenever it exceeds we increment cnt by 1 and change th
arrxy
NORMAL
2022-06-05T07:14:32.971875+00:00
2022-06-05T07:15:13.739752+00:00
47
false
We need to find subsequence so we can sort the array and use sliding window to keep check for max - min, whenever it exceeds we increment cnt by 1 and change the lo pointer\n```\nclass Solution {\npublic:\n\tint partitionArray(vector<int>& nums, int k) {\n\t\tsort(nums.begin(), nums.end());\n\t\tint cnt = 1, n = nums.size(), lo = 0;\n\t\tfor (int i = 1; i < n; ++i) {\n\t\t\tif (nums[i] - nums[lo] > k) {\n\t\t\t\tcnt++;\n\t\t\t\tlo = i;\n\t\t\t}\n\t\t}\n\t\treturn cnt;\n\t}\n};
1
0
['Greedy', 'C', 'Sliding Window']
0
partition-array-such-that-maximum-difference-is-k
C++ Easy | Sorting | Full explanation | Intution
c-easy-sorting-full-explanation-intution-1332
Task:\n\nReturn\xA0the\xA0minimum\xA0number of subsequences needed such that the difference between the maximum and minimum values in each subsequence is\xA0at
tejasmn
NORMAL
2022-06-05T06:58:36.349546+00:00
2022-06-05T07:07:18.487882+00:00
37
false
**Task:**\n\nReturn\xA0the\xA0minimum\xA0number of subsequences needed such that the difference between the maximum and minimum values in each subsequence is\xA0at most\xA0k.\n\n**Constraints:**\n\nlength<=10^5\nSo (10^5)^2 = 10^10 is not possible i.e O(n^2) fails.\nWe need to think in O(nlogn) or O(logn) or O(n)\ni.e sorting/logrithmic/linear\n\n**Approach:**\n\nWe only care about the count of subsequences where (max-min)<=k\n\nConsider,\n\n[3,6,1,2,5] k=2\n\nHere we see\nmax-min <=k\n\n3-1=2<=k\n6-5=1<=k\n2-2=0<=k\n\nSo subsequences are [3,1] [6,5] ,[2]\nBut we need minimum no. of subsequences \nSo we include 2 in [3,1] which doesn\'t change diff of max and min and 3-1=2<=k still holds true\n\nso new subseqnces are [3,1,2] and [6,5]\n\nSo we observed we included 2 in the range of min and max to minimise no. of subsequences\n\nThus we get the idea that we should consider only max and min and any other numbers that lie in this range should lie in the same subsequence for count to be min.\n\nThus if we sort the array\nleft part would be min and right part will be maximum\n\n[1,2,3,5,6]\n\nWe can check the following considering absolute difference abs(min-max)<=k\n\n1-2=1<=k\n1-3=2<=k\n1-5=4>k condition breaks means we have found one subsequence [1,2,3] here, so cnt++\n\nNow move to 5\n5-6=1<=k , cnt++ \n\nThus cnt=2 we found 2 subsequences [1,2,3] and [5,6]\n\n**>>Edge case:**\n\nConsider\n[1,2,3] k=1\n\n1-2=1<=k\n1-3=2>k condition breaks here cnt++\nEnd of array\n\ncnt =1\n\nBut wait we should have 2 subsequences \n[1,2] and [3] alone\n\nwe only found out [1,2]\n\nSo whenever condition breaks we do i--\nSo that the abs diff of element itself is checked\nsince single element can be a subsequence\n\nThus\n1-2=1<=k\n1-3=2>k cnt++ , i--\n3-3=0<=k cnt++\nThus cnt=2\n\nAlso we see sorting makes us consider each element in only one subsequence as mentioned in the question as we traverse linearly only once.\n\nAlso if we have just one element(max==min) in array ans will be always 1 independent of k since max-min will be 0.\n\n**Time Complexity:**\n\nSorting + linear\nO(nlogn)+O(n) = O(nlogn) \n\n**Code:**\n\n```\nclass Solution {\npublic:\n int partitionArray(vector<int>& nums, int k) {\n int n=nums.size();\n\t\tif(n==1) return 1;\n\t\t\n sort(nums.begin(),nums.end());\n int cnt=0;\n int idx=0;\n int diff;\n \n for(int i=1;i<n;i++)\n {\n diff= abs(nums[idx] - nums[i]);\n if(diff>k){\n cnt++;\n idx = i;\n i--;\n }\n\n }\n if(diff<=k) cnt++;\n \n return cnt;\n \n }\n};\n```
1
0
['Sorting']
0
maximum-number-of-tasks-you-can-assign
[Python] greedy + binary search, explained
python-greedy-binary-search-explained-by-sas1
The idea of this problem is the following: let us ask question: check(k): can we finish k tasks or not. Here is a couple of insights.\n\n1. If we want to finish
dbabichev
NORMAL
2021-11-13T16:23:10.324774+00:00
2021-11-13T16:42:25.862034+00:00
6,283
false
The idea of this problem is the following: let us ask question: `check(k)`: can we finish `k` tasks or not. Here is a couple of insights.\n\n1. If we want to finish `k` tasks, we better choose the smallest `k` of them.\n2. If we want to finish `k` tasks, we need `k` workers, and we want to choost the `k` strongest of them.\n3. So, we choose tasks and workers and now the question is can we allocate them. We start from the biggest task and start to allocate it to worker. First we try to give it to worker without pill and if we are OK, we allocate it to the weakest worker. If we can not allocate it to worker without pill, we allocate it to weakest worker with pill. If we can not do both of these steps, we return `False`: it means, that we were not able to allocate all tasks.\n\nGood question though, why this greedy strategy will work? At the moment I do not have strict proof, I will add it a bit later.\n\n#### Complexity\nIt is `O(n * log^2 n)` for time and `O(n)` for space.\n\n#### Code\n```python\nfrom sortedcontainers import SortedList\n\nclass Solution:\n def maxTaskAssign(self, tasks, workers, pills, strength):\n tasks = sorted(tasks)\n workers = sorted(workers)\n\n def check(k):\n W = SortedList(workers[-k:])\n tries = pills\n\n for elem in tasks[:k][::-1]:\n place = W.bisect_left(elem)\n if place < len(W):\n W.pop(place)\n elif tries > 0:\n place2 = W.bisect_left(elem - strength)\n if place2 < len(W):\n W.pop(place2)\n tries -= 1\n else:\n return False\n\n return len(W) == 0\n\n beg, end = 0, min(len(workers), len(tasks)) + 1\n while beg + 1 < end:\n mid = (beg + end)//2\n if check(mid):\n beg = mid\n else:\n end = mid\n\n return beg\n```\n\nIf you have any questoins, feel free to ask. If you like the solution and explanation, please **upvote!**
82
4
['Binary Search', 'Greedy']
18
maximum-number-of-tasks-you-can-assign
[C++] | Binary Search + Intuitive Greedy Idea | Detailed Explanation + Comments
c-binary-search-intuitive-greedy-idea-de-66tm
Idea\nThis is a good problem which requires concepts of binary search as well as greedy. I am going to try to explain the solution in points for better understa
astroash
NORMAL
2021-11-13T16:01:20.369927+00:00
2021-11-13T16:57:06.616750+00:00
5,794
false
**Idea**\nThis is a good problem which requires concepts of binary search as well as greedy. I am going to try to explain the solution in points for better understanding. \n\n* We binary seach over the number of tasks to be completed. Hence the search space would be [0, min(workers.size(), tasks.size()]. \n* Let us say that for a particular iteration of binary search, we need to check if *mid* number of tasks can be assigned. It makes sense to greedily choose the *mid* tasks with the smallest strength requirements. \n* For each task, there can be three cases:\n\t* A worker *without* the pill can complete it.\n\t* A worker *with* the pill can complete it.\n\t* No available worker, *with or without* the pill can complete it.\n* Since there is a constraint on the number of pills, it makes sense to give priority to the first case. If it is not possible, then we shift to the second case. However, if even that is not possible and we have third case, then we can say for sure that *mid* number of tasks cannot be assigned at all.\n* Keep in mind that for the first case, we can simply choose the strongest worker available. But for the second case (where we use the pill), it is always better to greedily look for the worker with the smallest strength that is capable of completing the current task. Assigning a task to a stronger worker when a weaker worker is capable can result in a situation later where there is a task which the weaker worker can\'t complete but the stronger worker could have completed. \n* We need to search for smaller values if the third case is reached or the number of pills required for *mid* tasks exceeds the given number of pills. Otherwise, we can check for higher values of *mid*.\n\n**Implementation**\nI use multiset to store the workers in each iteration of binary search. This is so that I can use the useful STL functions to make the implementation clear and concise. Also, multisets keep elements in increasing order by default. I have added comments to explain the code. \n\n**C++**\n```\nclass Solution {\npublic:\n int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int p, int strength) {\n int n = tasks.size(), m = workers.size();\n \n // Sorting the tasks and workers in increasing order\n sort(tasks.begin(), tasks.end());\n sort(workers.begin(), workers.end());\n int lo = 0, hi = min(m, n);\n int ans;\n \n while(lo <= hi) {\n int mid = lo + (hi - lo) / 2;\n int count = 0;\n bool flag = true;\n \n // Inserting all workers in a multiset\n multiset<int> st(workers.begin(), workers.end());\n \n // Checking if the mid smallest tasks can be assigned\n for(int i = mid - 1; i >= 0; i--) {\n \n // Case 1: Trying to assing to a worker without the pill\n auto it = prev(st.end());\n if(tasks[i] <= *it) {\n \n // Case 1 satisfied!\n st.erase(it);\n } else {\n \n // Case 2: Trying to assign to a worker with the pill\n auto it = st.lower_bound(tasks[i] - strength);\n if(it != st.end()) {\n \n // Case 2 satisfied!\n count++;\n st.erase(it);\n } else {\n \n // Case 3: Impossible to assign mid tasks\n flag = false;\n break;\n }\n }\n \n // If at any moment, the number of pills require for mid tasks exceeds \n // the allotted number of pills, we stop the loop\n if(count > p) {\n flag = false;\n break;\n }\n }\n \n if(flag) {\n ans = mid;\n lo = mid + 1;\n } else {\n hi = mid - 1;\n }\n }\n return ans;\n }\n};\n```\n\n*Space Complexity: O(m)*\n*Time Complexity: O(log(min(n, m)) * m * log(m))*\n\n**Complexity Analysis**\n*Space*: Auxiliary space is only required when creating a multiset for workers in each iteration of binary search. Hence, at any point of the program execution, there is O(m) auxiliary space used.\n\n*Time*: The search space of binary search is min(n, m), hence the factor of *log(min(n, m))*. In each iteration a multiset is created, hence the factor of *mlog(m)*. Further, the set is also binary searched for *mid* times, but this factor is ignored in the presence of *mlog(m)* when considering the amortized complexity.
70
1
['Binary Search', 'Greedy']
9
maximum-number-of-tasks-you-can-assign
Assign m easiest tasks
assign-m-easiest-tasks-by-votrubac-ki10
Liked this one. The binary search approach is not very obvious here.\n\nThe idea is to pick m easiest tasks, and m strongest workers, and see if we can assign t
votrubac
NORMAL
2021-11-14T23:20:01.615192+00:00
2021-11-14T23:20:50.713217+00:00
4,170
false
Liked this one. The binary search approach is not very obvious here.\n\nThe idea is to pick `m` easiest tasks, and `m` strongest workers, and see if we can assign those tasks.\n\nWith this set of `m` workers and tasks, we:\n1. Process tasks from hardest to easiest\n2. Check if the strongest worker can do the hardest of the remaining tasks.\n\t- If not, find the weakest worker that can do the hardest task if given a pill.\n\t- If there are no more pills, we cannot assign `m` tasks.\n3. If we find the worker who can do the task, remove it from the list of workers.\n\t- If not, we cannot assign `m` tasks.\n\nFinally, we do a binary search for the maximum number of tasks that we can accomplish.\n\n**C++**\n```cpp\nint maxTaskAssign(vector<int>& tasks, vector<int>& ws, int pills, int strength) {\n int l = 0, r = min(tasks.size(), ws.size());\n sort(begin(tasks), end(tasks));\n sort(begin(ws), end(ws));\n while (l < r) {\n int m = (l + r + 1) / 2, need = 0;\n multiset<int> ms(end(ws) - m, end(ws));\n for (int i = m - 1; i >= 0; --i) {\n auto it = prev(end(ms));\n if (*it < tasks[i]) {\n it = ms.lower_bound(tasks[i] - strength);\n if (it == end(ms) || ++need > pills)\n break;\n }\n ms.erase(it);\n }\n if (ms.empty())\n l = m;\n else\n r = m - 1;\n }\n return l;\n}\n```
48
1
[]
5
maximum-number-of-tasks-you-can-assign
JAVA Solution with Monotonic Queue
java-solution-with-monotonic-queue-by-jw-vrsp
\nclass Solution {\n public int maxTaskAssign(int[] tasks, int[] workers, int pills, int strength) {\n int left = 0, right = Math.min(tasks.length, wo
jw84
NORMAL
2021-12-08T04:55:36.159380+00:00
2021-12-08T04:55:36.159431+00:00
2,003
false
```\nclass Solution {\n public int maxTaskAssign(int[] tasks, int[] workers, int pills, int strength) {\n int left = 0, right = Math.min(tasks.length, workers.length);\n Arrays.sort(tasks);\n Arrays.sort(workers);\n while(left+1<right)\n {\n int mid = left + (right - left)/2;\n if(canAssign(mid, tasks, workers, pills, strength))\n {\n left = mid;\n }\n else\n {\n right = mid;\n }\n }\n \n if(canAssign(right, tasks, workers, pills, strength))\n {\n return right;\n }\n else return left;\n }\n \n public boolean canAssign(int count, int[] tasks, int[] workers, int pills, int strength){\n Deque<Integer> dq = new ArrayDeque<>();\n int ind = workers.length - 1;\n for (int i = count - 1; i >= 0; i--) {\n while(ind>=workers.length-count && workers[ind]+strength>=tasks[i])\n {\n dq.offerLast(workers[ind]);\n ind--;\n }\n \n if(dq.isEmpty())return false;\n if(dq.peekFirst()>=tasks[i])\n {\n dq.pollFirst();\n }\n else\n {\n dq.pollLast();\n pills--;\n if(pills<0)return false;\n }\n }\n \n return true;\n }\n}\n```
27
0
[]
5
maximum-number-of-tasks-you-can-assign
Python | Binary Search + Check Answer Greedily
python-binary-search-check-answer-greedi-roc4
Observation 1:\nIf we know how many tasks can be assigned (i.e. we know the ans = k in advanced), the best way to choose tasks and workers is:\n * Choose the
zoo30215
NORMAL
2021-11-13T16:10:33.644169+00:00
2021-11-14T08:41:19.579068+00:00
1,684
false
* Observation 1:\nIf we know how many tasks can be assigned (i.e. we know the `ans = k` in advanced), the best way to choose tasks and workers is:\n * Choose the `k` smallest tasks.\n * Choose the `k` strongest workers.\n * For example, if we need to finish `3` tasks among `tasks = [5,5,8,9,9]` with `workers = [1,2,4,6,6]`, we should choose `workers = [4, 6, 6]` to finish `tasks = [5, 5, 8]`\n \n* Observation 2:\nSuppose the tasks should be done is a multi-set `T`, and the workers is a sorted list `W`. For example, `T = [5, 5, 8]` and `W = [4, 6, 6]`, and `pills = 1, strength = 5`\n * Start from the weakest worker with strength of `4`. At this time, `T = [5, 5, 8]` and the minimum task of `T` is `5`. The worker should have a pill to finish a task. However, the worker after having a pill will have a strength of `9`. We can choose to assign the maximum task that the strengthened worker can do instead of the original task, to reduce the following strength requirements. In this case, we remove `8` from `T`.\n * The next worker has the strength of `6`. At this time, `T = [5, 5]` and the minimum task of `T` is `5`. The worker can finish the task without pill. Just remove the task from `T`.\n * The last worker has the strength of `6`. At this time, `T = [5]` and the minimum task of `T` is `5`. The worker can finish the task without pill. Just remove the task from `T`.\n \n* Combine the two observations, the solution of this question consists of two parts:\n * Binary search the answer `k`.\n * For every guess `k`, we check if `k` is valid or not.\n The two observations above is used in the process of checking.\n \n \n* How to find the maximum task that a strengthened worker can do? And how to remove the task efficiently?\n * This requires an efficient data structure. In Python you can use `SortedList` with `bisect_right` and `remove` in `O(lg n)`. In C++ you can use a `multiset`.\n\n* Time complexity:\n * Checking if the answer is valid needs `O(N log N)`.\n * Binary search will check the answer `O(log N)` times.\n * The total time complexity is `O(N log^2 N)`\n\n* My code:\n```python\nclass Solution:\n def maxTaskAssign(self, tasks: List[int], workers: List[int], pills: int, strength: int) -> int:\n \n from sortedcontainers import SortedList\n \n tasks.sort()\n workers.sort()\n \n def check_valid(ans):\n \n _tasks = SortedList(tasks[:ans])\n _workers = workers[-ans:]\n remain_pills = pills\n \n for worker in _workers:\n task = _tasks[0]\n if worker >= task:\n # the worker can finish the min task without pill, just move on\n _tasks.pop(0)\n elif worker + strength >= task and remain_pills:\n # the worker cannot finish the min task without pill, but can solve it with pill\n # remove the max task that the strengthened worker can finish instead\n remove_task_idx = _tasks.bisect_right(worker + strength)\n _tasks.pop(remove_task_idx - 1)\n remain_pills -= 1\n else:\n return False\n return True\n \n lo, hi = 0, min(len(workers), len(tasks))\n while lo < hi:\n mid = (lo + hi + 1) // 2\n if check_valid(mid):\n lo = mid\n else:\n hi = mid - 1\n return lo\n```
26
0
[]
4
maximum-number-of-tasks-you-can-assign
C++ Why Binary Search?
c-why-binary-search-by-changoi-990r
Why Binary Search?\nWhenever the set of all possible values that can satisfy the requirements form a continuous range, we apply the binary search to find the op
changoi
NORMAL
2021-11-13T17:22:57.954082+00:00
2021-11-14T02:26:33.540540+00:00
2,006
false
**Why Binary Search?**\nWhenever the set of all possible values that can satisfy the requirements form a continuous range, we apply the binary search to find the optimal value out of those.\n\nLet\'s understand this with the current example.\n\n- Suppose someone says that you can complete K tasks with this particular input. Then, it is evident that we can complete K-1 tasks, K-2 tasks ... so on.\n\n- But we can\'t say that we can complete K+1 tasks (or K+j, for any j>0 && j<=n-K).\n\t- If someone also says that K is not the max possible number of tasks that can be completed, then we can say we can surely do K+1 tasks.\n\t\n\t - That means there is a tipping point X, such that for a particular input, we can complete K<=X tasks, but we can complete K>X tasks.\n\t \nNow, this is similar to finding peak elements in the array using binary search.\n\n**Algorithm**\n- X can take values l = 0, r = n\n\n- We check if "mid" number of tasks can be taken with the help of Check() function. [Explained in the subsequent paragraph.]\n\t- Yes: Then, we search for X in [mid+1, r] range\n\t- No: Then, we search for X in [l, mid] range\n\t\n- Check() function\n\t- Given a number K, we have to check whether we can complete K tasks.\n\t- Now, we will greedily take K tasks, which require lowest strength. That is, tasks[0] ... tasks[k-1], after we sort tasks array.\n\t- We will process these K tasks in the decreasing order of their strengths, i.e. from K-1 to 0.\n\t\t- Say, for particular i, we need not to use a pill.\n\t\t\t- Then, we will allocate it to the largest available worker.\n\t\t- Say, for a particular task i, we need to use pill.\n\t\t\t- Suppose there are two workers, w1 with strength 4 and w2 with strength 5. Now, after taking pill both of them can complete the task i.\n\t\t\t- Then, which one is optimal to take?\n\t\t\t\t- Obviously taking worker w1. Because, if we can do some work at a cheap amount then why we should spend extras.\n\t\t\t- The lower_bound() does the part mentioned above.\n\t- The greedy strategy for Check() works well. And, it easy to write a proof of its correctness. Do let me know, if you need the proof.\n\n**Time Complexity**\n- O(n*log(n)*log(m))\n\n**Code(Multiset)**\n```\nclass Solution {\npublic:\n \n int check(vector<int> &tasks, int take, vector<int> &worker, int pills, int power){\n //optimal to take first "take" tasks\n //satisfy the largest one first\n multiset<int> st(worker.begin(), worker.end());\n while(take>=1 && st.size()){\n auto it = st.end(); --it; \n \n //last element can satisfy\n if(tasks[take-1] <= *st.rbegin()) {}\n //last worker cant satisfy, use pills\n else if(pills) { \n //find worker with least strength which after eating pill, can do the current task\n it = st.lower_bound(tasks[take-1]-power); \n if(it==st.end()) return 0;\n --pills;\n }\n else return 0;\n st.erase(it);\n --take;\n }\n return take==0;\n }\n int maxTaskAssign(vector<int>& t, vector<int>& w, int p, int s) {\n int n = t.size();\n int m = w.size();\n sort(t.begin(), t.end());\n \n int l = 0, r = n, ans = 0;\n \n while(l<=r){\n int mid = l + (r-l)/2;\n int chk = check(t,mid,w,p,s); //check if we can take "mid" number of tasks. \n //Return 1 if we can take, 0 otherwise \n if(chk) {\n ans = mid;\n l = mid+1;\n }\n else {\n r = mid-1;\n }\n }\n return ans;\n \n }\n};\n```\n**Code(Map)**\n```\nclass Solution {\npublic:\n \n int check(vector<int> &tasks, int take, map<int,int> count, int pills, int power){\n //optimal to take first "take" tasks\n //satisfy the largest one first\n \n while(take>=1 && count.size()){\n auto it = count.end(); --it; \n \n //last element can satisfy\n if(tasks[take-1] <= it->first) {} \n //last worker cant satisfy, use pills\n else if(pills) { \n //find worker with least strength which after eating pill, can do the current task\n it = count.lower_bound(tasks[take-1]-power); \n if(it==count.end()) return 0;\n --pills;\n }\n else return 0;\n \n --take;\n (it->second)--;\n if(it->second == 0) \n count.erase(it);\n }\n return take==0;\n }\n int maxTaskAssign(vector<int>& t, vector<int>& w, int p, int s) {\n int n = t.size();\n int m = w.size();\n sort(t.begin(), t.end());\n map<int,int> Count;\n for(auto &strength : w) Count[strength]++;\n \n int l = 0, r = n, ans = 0;\n \n while(l<=r){\n int mid = l + (r-l)/2;\n int chk = check(t,mid,Count,p,s); //check if we can take "mid" number of tasks. \n //Return 1 if we can take, 0 otherwise \n if(chk) {\n ans = mid;\n l = mid+1;\n }\n else {\n r = mid-1;\n }\n }\n return ans;\n \n }\n};\n```
21
0
[]
3
maximum-number-of-tasks-you-can-assign
[C++] Binary search the answer
c-binary-search-the-answer-by-tudor67-ot9a
\u2714\uFE0F Solution 1 (Binary search the answer)\nThis is a nice problem which can be solved with binary search.\n\nMain ideas\n Observation 1\n\t Let\'s say
tudor67
NORMAL
2021-11-25T21:29:47.254611+00:00
2021-11-26T10:37:19.652559+00:00
1,458
false
## \u2714\uFE0F **Solution 1 (Binary search the answer)**\nThis is a nice problem which can be solved with binary search.\n\n**Main ideas**\n* Observation 1\n\t* Let\'s say that we have a method `isValid(k)` which returns true if the workers can complete k tasks\n(such that all conditions of the problem are satisfied) and false otherwise.\n\t* The answer of the problem is the `maximum value k` such that `isValid(k)` is `true`.\nWe can **check all possible values** of k and return the maximum valid k.\nUnfortunately this is **too slow**.\n\n* Observation 2\n\t* If we know that workers can complete k tasks then for sure they can complete k - 1, k - 2, ..., 1 tasks.\nIf we know that workers cannot complete k tasks then for sure they cannot complete k + 1, k + 2, ... T tasks.\n\t* If we call `isValid(k)` for all k in range [0, T] then we will have a **sorted sequence** with prefix values `true` and\nwith suffix (possibly empty) values `false`: [true, true, true, ..., true, true, false, false, ..., false].\n\t* This means that we can **binary search** the `maximum value k` such that `isValid(k)` is `true`.\nThis should be **fast enough** to pass all test cases.\n\n**Algorithm**\n1. Sort `tasks` (we need this for `isValid(..)` method);\n2. Sort `workers` (we need this for `isValid(..)` method);\n3. Set the search space of the binary search: `[0, min(T, W)]`;\n\t* the maximum number of completed tasks is the minimum between number of tasks and number of workers;\n\t* remember that a worker can complete at most one task;\n4. For each range `[l, r]` during the binary search:\n\t* set `mid =(l + r + 1) / 2`;\n\t* if `isValid(mid) == true` then we shrink the range to `[mid, r]`;\n\telse we shrink the range to `[l, mid - 1]`;\n\t* when we shrink the range `[l, r]` we maintain the following invariant:\n\t\t * the left border `l` of the next range satisfies the condition/invariant `isValid(l) == true`;\n5. The binary search stops when the search range has a size equal to 1.\n * We can be sure that it represents the maximum number of tasks that can be completed by the workers.\n * Remember that we updated the ranges by moving to the right and maintaining the invariant `isValid(l) == true`.\n\nThe most interesting and difficult part of the problem is to implement the method `isValid(k)`. \nWe can use the following greedy approach:\n* Fix the `easiest k tasks` and `strongest k workers`;\n\t* this is why we sorted `tasks` and `workers` in the beginning;\n\t* we use a multiset with the strongest k workers (multiset allows fast search and erase operations);\n* `For each task` from the easiest k tasks (starting `from the hardest` and moving `to the easiest`):\n\t* search the `weakest available worker` that can complete the task `without taking a pill`;\n\t* if we find such worker\n\t\t* complete the task and erase him from the multiset (he is not available anymore);\n\t* if we do not find such worker:\n\t\t* if we do not have any pills then `return false` (we cannot complete the current task);\n\t\t* search the `weakest available worker` that can complete the task when he `takes a pill`;\n\t\t* if such worker exists then he takes a pill and completes the task (he is erased from the multiset, he is not available anymore)\n\t\totherwise `return false` (we cannot complete the current task);\n* If we completed all k tasks then `return true`;\n\n**Complexity analysis**\n- Notation: T = tasks.size(), W = workers.size()\n- **Time complexity:** `O(Tlog(T) + Wlog(W) + min(T, W) * (log(min(T, W))) ^ 2)`\n\t* `O(Tlog(T))` for `sort(tasks ..)`;\n\t* `O(Wlog(W))` for `sort(workers ..)`;\n\t* `O(min(T, W) * (log(min(T, W))) ^ 2)` for binary search;\n\t\t* `log(min(T, W))` calls of `isValid(..)` method;\n\t\t* each `isValid(..)` call is `O(min(T, W) * log(min(T, W)))`;\n- **Extra-Space complexity:** `O(min(T, W)+log(T)+log(W))`\n\t* `O(min(T, W))` for `workersMultiset`;\n\t* `O(log(T))` for recursion stack of `sort(tasks ..)`;\n\t* `O(log(W))` for recursion stack of `sort(workers ..)`;\n\t* We modify the input vectors (`tasks` and `workers`) and do not include `O(T + W)` to the extra-space of the solution/algorithm.\n\n\n**Submission details**\n\t- 48 / 48 test cases passed.\n\t- Runtime: 1638 ms\n\t- Memory Usage: 282.1 MB\n\n**Code**\n```\nclass Solution {\nprivate:\n bool isValid(vector<int>& tasks, vector<int>& workers, const int& MAX_TASKS, int pills, int strength){\n multiset<int> workersMultiset(workers.end() - MAX_TASKS, workers.end());\n for(int i = MAX_TASKS - 1; i >= 0; --i){\n auto it = workersMultiset.lower_bound(tasks[i]);\n if(it == workersMultiset.end()){\n pills -= 1;\n it = workersMultiset.lower_bound(tasks[i] - strength);\n }\n if(it == workersMultiset.end() || pills < 0){\n return false;\n }\n workersMultiset.erase(it);\n }\n return true;\n }\n \npublic:\n int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills, int strength) {\n const int T = tasks.size();\n const int W = workers.size();\n \n sort(tasks.begin(), tasks.end());\n sort(workers.begin(), workers.end());\n \n int l = 0;\n int r = min(T, W);\n while(l != r){\n int mid = (l + r + 1) / 2;\n if(isValid(tasks, workers, mid, pills, strength)){\n l = mid;\n }else{\n r = mid - 1;\n }\n }\n \n return r;\n }\n};\n```\n
18
1
['Greedy', 'C', 'Binary Tree']
1
maximum-number-of-tasks-you-can-assign
[python] binary search + greedy with deque O(nlogn)
python-binary-search-greedy-with-deque-o-81bw
Use binary search with greedy check. Each check can be done in O(n) using a deque. Within a check, we iterate through the workers from the weakiest to the stron
hkwu6013
NORMAL
2021-11-20T16:13:00.963742+00:00
2021-11-20T16:14:05.084106+00:00
1,038
false
Use binary search with greedy check. Each check can be done in O(n) using a deque. Within a check, we iterate through the workers from the weakiest to the strongest. Each worker needs to take a task. \nThere are two cases:\n1. The worker can take the easiest task available: we assign it to the worker.\n2. The worker cannot even take the easiest task: we give a pill to him and let him take the hardest doable task.\n\nThe deque will hold from the easiest unassigned task to the toughest that can be done by the current worker with a pill. If the easiest task can be handled by the weakiest worker, we assign it to the worker and do a popleft, other wise, we use one pill and pop from the right.\n```\nclass Solution:\n def maxTaskAssign(self, tasks: List[int], workers: List[int], pills: int, strength: int) -> int:\n # workers sorted in reverse order, tasks sorted in normal order\n def can_assign(n):\n task_i = 0\n task_temp = deque()\n n_pills = pills\n for i in range(n-1,-1,-1):\n while task_i < n and tasks[task_i] <= workers[i]+strength:\n task_temp.append(tasks[task_i])\n task_i += 1\n \n if len(task_temp) == 0:\n return False\n if workers[i] >= task_temp[0]:\n task_temp.popleft()\n elif n_pills > 0:\n task_temp.pop()\n n_pills -= 1\n else:\n return False\n return True\n \n tasks.sort()\n workers.sort(reverse = True)\n \n l = 0\n r = min(len(tasks), len(workers))\n res = -1\n while l <= r:\n m = (l+r)//2\n if can_assign(m):\n res = m\n l = m+1\n else:\n r = m-1\n return res\n```
16
0
['Greedy', 'Binary Tree', 'Python3']
2
maximum-number-of-tasks-you-can-assign
[Python3] binary search
python3-binary-search-by-ye15-cdjc
I thought a greedy algo would be enough but have spent hours and couldn\'t get a solution. It turns out that the direction was wrong in the first place. Below i
ye15
NORMAL
2021-11-13T22:16:41.038271+00:00
2021-11-14T01:47:50.231819+00:00
1,094
false
I thought a greedy algo would be enough but have spent hours and couldn\'t get a solution. It turns out that the direction was wrong in the first place. Below implementation is based on other posts in the discuss. \n\nPlease check out this [commit](https://github.com/gaosanyong/leetcode/commit/e61879b77928a08bb15cc182a69259d6e2bce59a) for solutions of biweekly 65. \n```\nclass Solution:\n def maxTaskAssign(self, tasks: List[int], workers: List[int], pills: int, strength: int) -> int:\n tasks.sort()\n workers.sort()\n \n def fn(k, p=pills): \n """Return True if k tasks can be completed."""\n ww = workers[-k:]\n for t in reversed(tasks[:k]): \n if t <= ww[-1]: ww.pop()\n elif t <= ww[-1] + strength and p: \n p -= 1\n i = bisect_left(ww, t - strength)\n ww.pop(i)\n else: return False \n return True \n \n lo, hi = 0, min(len(tasks), len(workers))\n while lo < hi: \n mid = lo + hi + 1 >> 1\n if fn(mid): lo = mid\n else: hi = mid - 1\n return lo \n```
11
0
['Python3']
5
maximum-number-of-tasks-you-can-assign
Greedy, sorting, binary search and array [EXPLAINED]
greedy-sorting-binary-search-and-array-e-2na5
Intuition\nAssign as many tasks as possible to workers, utilizing their strength and the option to use pills to temporarily boost their capacity. By sorting the
r9n
NORMAL
2024-10-25T06:07:39.594573+00:00
2024-10-25T06:07:39.594602+00:00
171
false
# Intuition\nAssign as many tasks as possible to workers, utilizing their strength and the option to use pills to temporarily boost their capacity. By sorting the tasks and workers, we can efficiently match them based on their abilities while considering the limits imposed by the pills.\n\n# Approach\nSort the tasks and workers, use binary search to determine the maximum number of tasks that can be assigned, and for each potential assignment, check if it\u2019s valid by comparing tasks with workers while allowing the use of pills when necessary.\n\n# Complexity\n- Time complexity:\nThe solution runs in \uD835\uDC42 ( \uD835\uDC5B log \u2061 \uD835\uDC5B ) O(nlogn) due to sorting the arrays and \uD835\uDC42 ( \uD835\uDC5B log \u2061 \uD835\uDC58 ) O(nlogk) for checking assignments in the binary search, where \uD835\uDC5B n is the number of tasks or workers, and \uD835\uDC58 k is the maximum number of tasks considered.\n\n- Space complexity:\nThe space complexity is \uD835\uDC42 ( \uD835\uDC5B ) O(n) because of the additional arrays created during the checking process.\n\n# Code\n```typescript []\n/**\n * Maximize the number of tasks assigned to workers given their strength and the option to use pills.\n *\n * @param {number[]} tasks - An array of tasks where each task has a specific strength requirement.\n * @param {number[]} workers - An array of workers where each worker has a specific strength.\n * @param {number} pills - The number of pills available to boost worker strength.\n * @param {number} strength - The amount by which a pill boosts a worker\'s strength.\n * @return {number} - The maximum number of tasks that can be assigned to workers.\n */\nconst maxTaskAssign = function(tasks: number[], workers: number[], pills: number, strength: number): number {\n // Sort tasks in ascending order and workers in descending order\n tasks.sort((a, b) => a - b);\n workers.sort((a, b) => b - a);\n\n const m = tasks.length, n = workers.length; // Get the number of tasks and workers\n const { min, floor } = Math; // Destructure some useful Math functions\n let l = 0, r = min(n, m); // Initialize left and right pointers for binary search\n\n while (l < r) {\n const mid = r - floor((r - l) / 2); // Calculate the middle index\n if (check(mid)) l = mid; // If we can assign mid tasks, move left\n else r = mid - 1; // Otherwise, adjust right boundary\n }\n\n return l; // Return the maximum number of tasks that can be assigned\n\n /**\n * Helper function to check if it\'s possible to assign k tasks.\n *\n * @param {number} k - The number of tasks to check for assignment.\n * @return {boolean} - True if tasks can be assigned, otherwise false.\n */\n function check(k: number): boolean {\n const wArr = workers.slice(0, k); // Get the strongest k workers\n const tArr = tasks.slice(0, k); // Get the k weakest tasks\n let tries = pills; // Initialize remaining pills\n const bs = Bisect(); // Create a new instance of the Bisect helper class\n wArr.reverse(); // Reverse workers to prioritize the strongest\n tArr.reverse(); // Reverse tasks to prioritize the weakest\n\n // Iterate over tasks to attempt assignment\n for (let elem of tArr) {\n const place = bs.bisect_left(wArr, elem); // Find a worker for the current task\n\n // If a worker can handle the task without a pill\n if (place < wArr.length) {\n wArr.pop(); // Assign the worker to the task\n } else if (tries > 0) { // If no worker can handle it and we have pills left\n const place2 = bs.bisect_left(wArr, elem - strength); // Check if a worker can handle it with a pill\n if (place2 < wArr.length) {\n wArr.splice(place2, 1); // Assign the worker who can do the task with a pill\n tries -= 1; // Use a pill\n }\n } else {\n return false; // No assignment possible\n }\n }\n\n return wArr.length === 0; // Return true if all tasks are assigned\n }\n};\n\n// Helper class for binary search operations\nfunction Bisect() {\n return { insort_right, insort_left, bisect_left, bisect_right };\n\n function insort_right(a: number[], x: number, lo: number = 0, hi: number | null = null): void {\n lo = bisect_right(a, x, lo, hi); // Get the position to insert\n a.splice(lo, 0, x); // Insert the element at the correct position\n }\n\n function bisect_right(a: number[], x: number, lo: number = 0, hi: number | null = null): number {\n // > upper_bound\n if (lo < 0) throw new Error(\'lo must be non-negative\');\n if (hi == null) hi = a.length; // Set hi to the length of the array if not provided\n while (lo < hi) {\n let mid = Math.floor((lo + hi) / 2); // Calculate mid index\n x < a[mid] ? (hi = mid) : (lo = mid + 1); // Adjust lo and hi based on comparison\n }\n return lo; // Return the position for the insertion\n }\n\n function insort_left(a: number[], x: number, lo: number = 0, hi: number | null = null): void {\n lo = bisect_left(a, x, lo, hi); // Get the position to insert\n a.splice(lo, 0, x); // Insert the element at the correct position\n }\n\n function bisect_left(a: number[], x: number, lo: number = 0, hi: number | null = null): number {\n // >= lower_bound\n if (lo < 0) throw new Error(\'lo must be non-negative\');\n if (hi == null) hi = a.length; // Set hi to the length of the array if not provided\n while (lo < hi) {\n let mid = Math.floor((lo + hi) / 2); // Calculate mid index\n a[mid] < x ? (lo = mid + 1) : (hi = mid); // Adjust lo and hi based on comparison\n }\n return lo; // Return the position for the insertion\n }\n}\n\n```
8
0
['TypeScript']
0
maximum-number-of-tasks-you-can-assign
[Python Binary Search + Monotonic Queue] Template
python-binary-search-monotonic-queue-tem-hrsx
\nfrom collections import deque\nclass Solution:\n def maxTaskAssign(self, tasks: List[int], workers: List[int], pills: int, strength: int) -> int:\n
surface09
NORMAL
2022-03-26T21:32:16.431207+00:00
2022-05-26T20:59:06.467452+00:00
665
false
```\nfrom collections import deque\nclass Solution:\n def maxTaskAssign(self, tasks: List[int], workers: List[int], pills: int, strength: int) -> int:\n \n tasks.sort()\n workers.sort()\n \n def can_finish(mid, pills):\n \n n = len(workers)\n \n i = 0\n \n # record the mid valid tasks\n queue = deque()\n \n for j in range(n - mid, n):\n \n w = workers[j]\n \n # put m tasks into the queue\n while i < mid and tasks[i] <= w + strength:\n queue.append(tasks[i])\n i += 1\n \n # Now we have found the eligible at most m tasks that workers[j] can finish\n # and have put these tasks into the queue\n \n \n # below are to find the most smallest strength task that workers[j] can finish\n \n # First check, if no tasks were added, this means workers[j] can finish nothing\n if not queue:\n return False\n \n # Case 1: if workers[j] can finish task queue[0] without eating pills,\n # then this is what we want, that is, the powerful worker finish the smallest task.\n if queue[0] <= w:\n queue.popleft()\n \n # Case 2: if workers[j] needs to eat pills to finish\n # Once he needs to eat pill, we choose the hardest task for him\n # since the left tasks for the others workers will be easy to finish.\n else:\n # need to eat pills\n if pills == 0:\n return False\n \n pills -= 1\n queue.pop()\n \n # after this loop, it means for the workers[j], \n # he can finish the one task that is <= his strength + strength of pills\n \n return True\n \n \n # standard Binary Search\n left = 0\n right = min(len(tasks), len(workers))\n \n while left + 1 < right:\n \n mid = left + (right - left) // 2\n \n # this guessing mid number is eligible, \n # we can guess larger since we need maximum tasks number\n if can_finish(mid, pills):\n left = mid\n \n else:\n right = mid - 1\n \n if can_finish(right, pills):\n return right\n else:\n return left\n```
4
0
['Binary Search', 'Python']
1
maximum-number-of-tasks-you-can-assign
why binary search and why not direct greedy approach? EXPLAINED
why-binary-search-and-why-not-direct-gre-o0z5
greedy approach will not work here why? read below\n\ne.x if we prioritize on the basis of workers array , the worker[i] will try to do the work just smaller th
vikassingh2810
NORMAL
2022-01-31T14:37:20.055135+00:00
2022-02-02T05:40:31.678599+00:00
427
false
greedy approach will not work here why? read below\n\ne.x if we prioritize on the basis of workers array , the worker[i] will try to do the work just smaller then its strenght \nbut the problem occur when a worker can do a task with and without a pill :\n\nfor e g \n\ntask [ 8 5 5 ]\nworker [ 6 6 4 ]\npill =1\nstre = 4\n\nans = 3 ( since worker [ 0 ] can do both task task[ 0 ] with pill and task [1] without pill \n but we get optimal answere when we give pill to worker [ 2 ] instead of \n\t\t\t\t\t\t\t worker [0] )\n\t\t\t\t\t\t\t \n\t\t\t\t\t\t\t \n\t\t\t\t\t\t\t other eaxmple;\n\t\ntask [ 10 5 4 ]\nworker [ 7 6 4 ]\npill =1\nstre = 3\n\nans= 3 ( since worker [ 0 ] can do both task task[ 0 ] with pill and task [1] without pill \n but we get optimal answere when we we give pill to worker [ 0 ])\n\t\t\t\t\t\t\t \n these 2 example are contradiction to each other in one we get optimal answere by giving pill to worker 0 and in other by giving pill to worker 2\n\t\t\t\t\t\t\t \nso this proves prioritizing approach will not work here\n\t\t\t\t\t\t\t \n\nhow do binary search work \n\n if we sort the array and if kth worker cant do a task with and without a pill its confirm that all worker with strenght less then kth worker will also not we able to do that task;\n\t \n\t and if we say that k task can be done so we can chosse k strongest workers and k weakest tasks and now we each work have to do its corresponding task so either it will do it on its own or with a help of a pill workers dont have options now\n\t \n\tworker [ a b c d e ]\n\ttask [ v x y z ]\n\t\n\tcan we do 3 tasks so we chosse worker [ a b c] task [ x y z ]\n\t\n\tnow each task is to be done else we return false;\n\t\n\tso if a task can we assigned to a worker we assign it else we subtract pill strength from task and assign it to a optimal worker ( that is the weakest worker capable of doing the task)\n\t\n\t\n\t\n`class Solution {\n public:\n bool solver(vector<int>& t, vector<int>& w,int m,int p,int s)\n {\n int k=w.size();\n \n multiset<int>st(w.begin()+k-m,w.end());\n \n for(int i=m-1;i>=0;i--)\n {\n auto it=st.end();\n it--;\n if(*it<t[i])\n {\n auto temp=st.lower_bound(t[i]-s);\n if(!p || temp==st.end())\n return false;\n else\n {\n p--;\n st.erase(temp);\n }\n }\n else\n st.erase(it);\n \n }\n return true;\n }\n int maxTaskAssign(vector<int>& tasks, vector<int>& work, int pill, int s) {\n \n int l=0;\n \n int r=min(tasks.size(),work.size());\n \n int n=work.size();\n sort(tasks.begin(),tasks.end());\n sort(work.begin(),work.end());\n \n int ans=0;\n \n while(l<=r)\n {\n int m=(l+r)/2;\n bool flag=true;\n \n multiset<int>st(work.begin()+n-m,work.end());\n int p=pill;\n for(int i=m-1;i>=0;i--)\n {\n auto it=st.end();\n it--;\n \n \n if(*it<tasks[i])\n {\n auto temp=st.lower_bound(tasks[i]-s);\n if(!p || temp==st.end())\n {\n flag=false;\n break;\n }\n else\n {\n p--;\n st.erase(temp);\n }\n }\n else\n st.erase(it);\n \n }\n \n \n if(flag)\n {\n l=m+1;\n ans=max(m,ans);\n }\n else\n r=m-1;\n }\n \n return ans;\n }\n};`\n\t\t\t\t\t\t\t \t\n\t\t\t\t\t\t\t
4
0
[]
0
maximum-number-of-tasks-you-can-assign
[Python] Binary Search with Double Deque to Trace Available Workers
python-binary-search-with-double-deque-t-5axv
Explained in the comments:\n\nclass Solution:\n def maxTaskAssign(self, tasks: List[int], workers: List[int], pills: int, strength: int) -> int:\n tas
alenny
NORMAL
2021-12-13T02:19:32.256138+00:00
2021-12-13T02:19:32.256164+00:00
338
false
Explained in the comments:\n```\nclass Solution:\n def maxTaskAssign(self, tasks: List[int], workers: List[int], pills: int, strength: int) -> int:\n tasks = list(sorted(tasks))\n workers = list(sorted(workers))\n WN = len(workers)\n \n # to evaluate if k tasks can be done, we just need to check if the strongest k workers \n # can finish the k smallest tasks\n def canDo(k: int) -> bool:\n ps = pills\n # wq stores the k strongest workers in desc order\n wq = deque(workers[WN - k:][::-1])\n # available stores workers which can do the current task with pill help\n available = deque()\n for t in tasks[:k][::-1]:\n while wq and wq[0] + strength >= t:\n available.append(wq.popleft())\n if not available:\n return False\n if available[0] >= t: # no need to use pill\n available.popleft()\n elif ps > 0:\n # when pill is needed, use the weakest available worker\n ps -= 1\n available.pop() \n else:\n return False\n return True\n \n N = len(tasks)\n l, r = 0, N\n while l <= r:\n mid = l + r >> 1\n if canDo(mid):\n l = mid + 1\n else:\n r = mid - 1\n return r\n```
3
0
[]
0
maximum-number-of-tasks-you-can-assign
C++ greedy without binary-search
c-greedy-without-binary-search-by-mrsuyi-kdpn
I would say binary search is a much better solution... but still it\'s possible to use greedy only.\n\n1. Sort tasks in increasing order. Put workers in a set s
mrsuyi
NORMAL
2021-11-22T00:23:56.812298+00:00
2021-11-23T04:39:41.279904+00:00
554
false
I would say binary search is a much better solution... but still it\'s possible to use greedy only.\n\n1. Sort `tasks` in increasing order. Put `workers` in a set `st` as a pool of candidate workers.\n2. Keep a set `taken` of workers which have taken a pill to match a task.\n3. Loop through `tasks` from biggest to smallest. Find a matching worker by:\n\ta. Use the biggest one in `st` if it can do it without a pill.\n\tb. Find the smallest one in `st` that can do it with a pill.\n\tc. If there is no such one from #b, and the biggest in `taken` can do current task without a pill, it should be changed to do current task and yield the pill it has taken.\n\td. If there is one from #b, and there are pills left, feed it a pill.\n\te. If there is one from #b, but there is no pill left. Compare the largest in `taken`, the one from #b, and current task to decide which one should take the pill and which one should be put into `st`.\n\n```cpp\nclass Solution {\npublic:\n int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills, int strength) {\n sort(tasks.begin(), tasks.end());\n multiset<int> st(workers.begin(), workers.end());\n multiset<int> taken;\n int n = tasks.size(), m = workers.size();\n int res = 0;\n for (int i = n - 1; i >= 0 && !st.empty(); --i) {\n if (*st.rbegin() >= tasks[i]) {\n ++res;\n st.erase(prev(st.end()));\n continue;\n }\n auto it = st.lower_bound(tasks[i] - strength);\n if (it == st.end()) {\n if (!taken.empty() && *taken.rbegin() >= tasks[i]) {\n taken.erase(prev(taken.end()));\n ++pills;\n }\n continue;\n }\n if (pills == 0) {\n if (taken.empty()) {\n continue;\n }\n if (*taken.rbegin() >= tasks[i]) {\n ++pills;\n taken.erase(prev(taken.end()));\n } else {\n int ma = max(*it, *taken.rbegin());\n int mi = min(*it, *taken.rbegin());\n taken.erase(prev(taken.end()));\n taken.insert(mi);\n st.erase(it);\n st.insert(ma);\n }\n continue;\n }\n taken.insert(*it);\n st.erase(it);\n ++res;\n --pills;\n }\n return res;\n }\n};\n```
3
1
[]
2
maximum-number-of-tasks-you-can-assign
✅ [Python] Binary Search || Faster than 100% || Easy to Understand with Explanation
python-binary-search-faster-than-100-eas-utfz
\nclass Solution(object):\n def maxTaskAssign(self, tasks, workers, pills, strength):\n def canAssignAll(tasks, workers, pills):\n # notic
linfq
NORMAL
2021-11-19T03:55:30.948052+00:00
2021-11-19T07:14:57.613297+00:00
488
false
```\nclass Solution(object):\n def maxTaskAssign(self, tasks, workers, pills, strength):\n def canAssignAll(tasks, workers, pills):\n # notice that len(tasks) = len(workers)\n # given pills and strength, can all tasks be assigned, so that every worker has a task.\n while len(tasks) and len(workers):\n if workers[-1] >= tasks[-1]:\n # from the max task to the min, if current max worker can do the current max task, \n # assign the max task to the max worker.\n workers.pop()\n tasks.pop()\n elif pills > 0:\n # if current max worker cannot do the current max task, someone should eat a pill to try, but it is\n # no need that the current max worker goes to eat the pill, it\'s not greedy. we need to find the \n # greedy worker who is the min one can do the current max task after eat a pill, and assign it to \n # him.\n pills -= 1\n j = bisect.bisect_left(workers, tasks[-1] - strength)\n if j >= len(workers):\n # it means even the current max worker cannot do the current max task after eat a pill.\n return False\n workers.pop(j)\n tasks.pop()\n else: # it means the current max worker cannot do the current max task, and no pill left.\n return False\n return True\n\n tasks.sort()\n workers.sort()\n # standard binary search\n low, high = 0, min(len(tasks), len(workers))\n while low <= high:\n mid = (low + high) // 2\n if canAssignAll(tasks[:mid], workers[-mid:], pills):\n\t\t\t # try assign mid easiest tasks to mid strongest workers, it\'s a naive greedy strategy.\n low = mid + 1\n else:\n high = mid - 1\n return high\n```\n**If you have any questoins, feel free to ask. If you like the solution and explanation, please upvote!**
3
0
[]
1
maximum-number-of-tasks-you-can-assign
Python | Easy | Queue | Maximum Number of Tasks You Can Assign
python-easy-queue-maximum-number-of-task-vxgj
\nsee the Successfully Accepted Submission\nPython\nfrom sortedcontainers import SortedList\n\nclass Solution:\n def maxTaskAssign(self, tasks, workers, p, s
Khosiyat
NORMAL
2023-10-11T15:19:26.888013+00:00
2023-10-11T15:19:26.888030+00:00
246
false
\n[see the Successfully Accepted Submission](https://leetcode.com/submissions/detail/1071707824/)\n```Python\nfrom sortedcontainers import SortedList\n\nclass Solution:\n def maxTaskAssign(self, tasks, workers, p, strength):\n n = len(tasks)\n m = len(workers)\n\n # Sorting the tasks and workers in increasing order\n tasks.sort()\n workers.sort()\n lo = 0\n hi = min(m, n)\n ans = None\n\n while lo <= hi:\n mid = lo + (hi - lo) // 2\n count = 0\n flag = True\n\n # Inserting all workers in a sorted list\n st = SortedList(workers)\n\n # Checking if the mid smallest tasks can be assigned\n for i in range(mid - 1, -1, -1):\n\n # Case 1: Trying to assign to a worker without the pill\n it = st[-1]\n if tasks[i] <= it:\n\n # Case 1 satisfied!\n st.remove(it)\n else:\n\n # Case 2: Trying to assign to a worker with the pill\n it = st.bisect_left(tasks[i] - strength)\n if it != len(st):\n\n # Case 2 satisfied!\n count += 1\n st.pop(it)\n else:\n\n # Case 3: Impossible to assign mid tasks\n flag = False\n break\n\n # If at any moment, the number of pills required for mid tasks exceeds\n # the allotted number of pills, we stop the loop\n if count > p:\n flag = False\n break\n\n if flag:\n ans = mid\n lo = mid + 1\n else:\n hi = mid - 1\n\n return ans\n\n```\n\n![image](https://assets.leetcode.com/users/images/b1e4af48-4da1-486c-bc97-b11ae02febd0_1696186577.992237.jpeg)\n\n\n
2
0
['Queue', 'Python']
0
maximum-number-of-tasks-you-can-assign
🔥🔥🔥C++ | super easy | clean code | multi set | easy to grasp🔥🔥🔥
c-super-easy-clean-code-multi-set-easy-t-166f
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
Algo-Messihas
NORMAL
2023-08-13T16:06:04.471504+00:00
2023-08-13T16:06:04.471538+00:00
767
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 {\nprivate:\n bool isPossible(int numTask, vector<int>& tasks, vector<int>& workers, int pills, int strength){\n multiset<int> ms(workers.end()-numTask,workers.end());\n\n for(int i=numTask-1; i>=0; i--){\n auto it = ms.end();\n it--;\n if(*it < tasks[i]){\n if(!pills) return false;\n it = ms.lower_bound(tasks[i]-strength);\n if(it == ms.end()) return false;\n pills--;\n }\n ms.erase(it);\n }\n\n return true;\n }\npublic:\n int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills, int strength) {\n \n sort(tasks.begin(), tasks.end());\n sort(workers.begin(),workers.end());\n\n int n = tasks.size();\n int m = workers.size();\n\n int low = 0;\n int high = min(n,m);\n int ans = 0;\n\n while(low <= high){\n int mid = (low + high) >> 1;\n if(isPossible(mid,tasks,workers,pills,strength)){\n ans = mid;\n low = mid + 1;\n }\n else high = mid - 1;\n }\n return ans;\n }\n};\n```
2
0
['C++']
0
maximum-number-of-tasks-you-can-assign
[Javascript] Binary Search & Deque
javascript-binary-search-deque-by-anna-h-m5vb
Solution: Binary Search & Deque\n\nBinary search for the largest number of tasks that can be completed.\nHow to check whether we can complete k tasks:\n Try t
anna-hcj
NORMAL
2022-10-30T10:13:30.016231+00:00
2022-10-30T10:13:56.304597+00:00
160
false
**Solution: Binary Search & Deque**\n\nBinary search for the largest number of tasks that can be completed.\nHow to check whether we can complete k tasks:\n* Try to assign the k weakest tasks to the k strongest workers.\n* Sort tasks in asc order and workers in desc order.\n* Go through the workers from weakest to strongest,\n\t* Try to assign the easiest task to the worker (without using a pill).\n\t\t* If it can be assigned, assign it. (If the easiest task can be done by the worker, that means all following workers will be able to do it without a pill. Therefore, it is optimal for the current task to complete the easiest task)\n\t\t* Otherwise, try to do the hardest possible task after using a pill.\n* Keep track of the tasks that are assignable after using a pill in a deque so that we can remove tasks both on the left and right.\n If we can\'t assign any task to the worker, return false (we can\'t complete k tasks).\n\n`n = number of tasks`, `m = number of workers`\nTime Complexity: `O(n log(n) + m log(m))` 479ms\nSpace Complexity: `O(m)` 65.7MB\n```\nvar maxTaskAssign = function(tasks, workers, pills, strength) {\n let m = workers.length;\n tasks.sort((a, b) => a - b);\n workers.sort((a, b) => b - a);\n let low = 0, high = m;\n while (low < high) {\n let mid = Math.ceil((low + high) / 2);\n if (canAssign(mid)) low = mid;\n else high = mid - 1;\n }\n return low;\n \n function canAssign(k) {\n let queue = new Deque(), pillsUsed = 0;\n for (let j = k - 1, i = 0; j >= 0; j--) {\n while (i < k && workers[j] + strength >= tasks[i]) {\n queue.push(tasks[i++]);\n }\n if (queue.isEmpty()) return false; // no do-able tasks\n if (queue.front() <= workers[j]) { // do the easiest task without using pill\n queue.shift();\n } else if (pillsUsed === pills) { \n return false;\n } else { // do the hardest task after using a pill\n pillsUsed++;\n queue.pop();\n }\n }\n return true;\n }\n};\n\nclass Deque {\n constructor() {\n this.head = new Node(null);\n this.tail = new Node(null);\n this.head.next = this.tail;\n this.tail.prev = this.head;\n this.size = 0;\n }\n unshift(val) {\n let node = new Node(val);\n node.next = this.head.next;\n node.prev = this.head;\n this.head.next.prev = node;\n this.head.next = node;\n this.size++;\n }\n push(val) {\n let node = new Node(val);\n node.prev = this.tail.prev;\n node.next = this.tail;\n this.tail.prev.next = node;\n this.tail.prev = node;\n this.size++;\n }\n shift() {\n let head = this.head.next;\n this.removeNode(head);\n this.size--;\n return head.val;\n }\n pop() {\n let tail = this.tail.prev;\n this.removeNode(tail);\n this.size--;\n return tail.val;\n }\n removeNode(node) {\n if (!node.prev && !node.next) return;\n node.prev.next = node.next;\n node.next.prev = node.prev;\n node.prev = null;\n node.next = null;\n }\n front() {\n return this.head.next.val;\n }\n back() {\n return this.tail.prev.val;\n }\n isEmpty() {\n return this.size === 0;\n }\n}\nclass Node {\n constructor(val) {\n this.val = val;\n this.next = null;\n this.prev = null;\n }\n}\n```
2
0
['JavaScript']
0
maximum-number-of-tasks-you-can-assign
[C++] | Binary Search | Noob Friendly
c-binary-search-noob-friendly-by-grimo-i9ht
\nclass Solution {\npublic:\n bool isPossible(int noOfTasks,vector<int>& tasks, vector<int>& workers, int pills, int strength){\n multiset <int> ms(wo
grimo
NORMAL
2022-06-14T22:16:04.661942+00:00
2022-06-14T22:16:04.661966+00:00
612
false
```\nclass Solution {\npublic:\n bool isPossible(int noOfTasks,vector<int>& tasks, vector<int>& workers, int pills, int strength){\n multiset <int> ms(workers.end()-noOfTasks,workers.end());\n for(int i=noOfTasks-1;i>=0;i--){\n //get the strongest worker\n auto it = ms.end();\n it--;\n \n //if the strongest worker cannot do the task\n if(*it<tasks[i]){\n if(pills<=0)\n return false;\n //find the weakest worker who is just able to do the task with pill\n it=ms.lower_bound(tasks[i]-strength);\n if(it==ms.end())\n return false;\n \n //task done decrese the pill\n pills--;\n }\n //remove the worker from the multiset\n ms.erase(it);\n }\n return true;\n \n } \n int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills, int strength) {\n int l=0,r= min(tasks.size(),workers.size());\n int res=0;\n sort(tasks.begin(),tasks.end());\n sort(workers.begin(),workers.end());\n while(l<=r){\n int mid= (l+r)/2;\n if(isPossible(mid,tasks,workers,pills,strength)){\n res=mid;\n l=mid+1;\n }else{\n r=mid-1;\n }\n }\n return res;\n }\n};\n```
2
0
['Greedy', 'Binary Tree']
0
maximum-number-of-tasks-you-can-assign
Java | TreeMap | Binary Search
java-treemap-binary-search-by-6862wins-qrla
```\n public int maxTaskAssign(int[] tasks, int[] workers, int pills, int strength) {\n Arrays.sort(tasks);\n TreeMap map = new TreeMap<>();\n
6862wins
NORMAL
2022-01-29T06:12:37.134964+00:00
2022-01-29T06:12:37.134994+00:00
545
false
```\n public int maxTaskAssign(int[] tasks, int[] workers, int pills, int strength) {\n Arrays.sort(tasks);\n TreeMap<Integer, Integer> map = new TreeMap<>();\n for (int i : workers)\n \tmap.put(i, map.getOrDefault(i, 0) + 1);\n int res = 0, left = 0, right = Math.min(tasks.length, workers.length) - 1; \n while (left <= right) {\n \tint mid = (left + right) / 2;\n \tif (validate(tasks, (TreeMap<Integer, Integer>)map.clone(), pills, strength, mid))\n \t\tres = left = mid + 1;\n \telse\n \t\tright = mid - 1;\n }\n return res;\n }\n boolean validate(int[] tasks, TreeMap<Integer, Integer> map, int pills, int strength, int pos) {\n \tfor (; pos >= 0; pos--) {\n\t \tint maxStrength = map.lastKey(), t = tasks[pos];\n\t \tif (pills > 0 && strength + maxStrength < t || pills == 0 && maxStrength < t)\n\t \t\treturn false;\n\t \tif (maxStrength < t) {\n\t \t\tt -= strength;\n\t \t\tpills--;\n\t \t}\n \t\tint matchStrength = map.ceilingKey(t);\n \t\tif (map.get(matchStrength) > 1)\n \t\t\tmap.put(matchStrength, map.get(matchStrength) - 1);\n \t\telse\n \t\t\tmap.remove(matchStrength);\n \t}\n \treturn true;\n }\n
2
0
['Binary Search', 'Tree', 'Java']
0
maximum-number-of-tasks-you-can-assign
Greedy Binary Search Java Solution
greedy-binary-search-java-solution-by-lu-fta1
\n\nclass Solution {\n public int maxTaskAssign(int[] tasks, int[] workers, int pills, int strength) {\n Arrays.sort(tasks);\n Arrays.sort(work
luciddream
NORMAL
2022-01-08T09:33:21.399511+00:00
2022-01-08T09:38:02.180023+00:00
454
false
\n```\nclass Solution {\n public int maxTaskAssign(int[] tasks, int[] workers, int pills, int strength) {\n Arrays.sort(tasks);\n Arrays.sort(workers);\n int m = tasks.length, n = workers.length;\n int start = 0, end = Math.min(m, n);\n while(start < end) {\n int mid = (end - start) / 2 + start;\n boolean isDone = true; \n TreeMap<Integer, Integer> map = new TreeMap<>();\n for(int w : workers) {\n map.put(w, map.getOrDefault(w, 0) + 1);\n }\n int tries = pills;\n for(int i = mid; i >= 0; i--) {\n int w = map.lastKey();\n if(tasks[i] <= w) {// use the strongest workers for "easy tasks"\n map.put(w, map.get(w) - 1);\n if(map.get(w) == 0) map.remove(w);\n } else { // use pill for qualify workers if the worker exists. If not, we exit the for-loop and try smaller size of tasks \n Integer w1 = map.ceilingKey(tasks[i] - strength);\n if(w1 != null) {\n tries --;\n map.put(w1, map.get(w1) - 1);\n if(map.get(w1) == 0) map.remove(w1);\n } else {\n isDone = false;\n break;\n }\n }\n if(tries < 0) {\n isDone = false;\n break;\n }\n }\n if(isDone) {\n start = mid + 1;\n } else {\n end = mid;\n }\n }\n return start;\n }\n}\n```
2
0
['Java']
0
maximum-number-of-tasks-you-can-assign
Java Easy Solution + Explanation
java-easy-solution-explanation-by-octavi-huoq
Approach:\n1. So we know that the min task that can be done is 0 and the max task that can be done is min size between worker or tasks. \n2. Sort both arrays no
Octavius25
NORMAL
2021-11-28T08:42:13.561778+00:00
2021-11-28T08:42:13.561810+00:00
575
false
**Approach:**\n**1. So we know that the min task that can be done is 0 and the max task that can be done is min size between worker or tasks. \n2. Sort both arrays now using binary search we need to find that a whether he is able to complete task(low+high)/2 or not if he is able to complete that task then try for some other task that comes in range (low+1,high)\n3. If the person with max strength is not able to complete the task(mid) then try to complete task using pill and for that just feed the pill to the worker with the least strength so that he can complete the task (mid) .**\n```\nclass Solution {\n static int firstPowerguy(int w[],int s,int reqstrength){\n for(int i=0;i<w.length;i++){\n if(w[i]==-1)\n continue;\n else if(w[i]+s>=reqstrength){\n return i;\n }\n }\n return -1;\n }\n static boolean canThisMuchTaskBeDone(int mid,int workers[],int tasks[],int pills,int strength){\n //lets find can i do mid task or not\n int end=workers.length-1;\n // System.out.println(mid);\n while(mid>0){\n if(workers[end]==-1){\n end--;\n continue;\n }\n if(tasks[mid-1]<=workers[end]){\n end--;\n mid--;\n }\n else{\n if(pills<=0)\n return false;\n else{\n \n int ind=firstPowerguy(workers,strength,tasks[mid-1]);\n // System.out.println("pow"+ind);\n if(ind!=-1){\n pills--;\n tasks[mid-1]=-1;\n mid--;\n workers[ind]=-1;\n \n }\n else{\n return false;\n }\n }\n } \n }\n return true;\n }\n public int maxTaskAssign(int[] tasks, int[] workers, int pills, int strength) {\n int low=0;\n int high=Math.min(tasks.length,workers.length);\n Arrays.sort(tasks);\n Arrays.sort(workers);\n int ans=0;\n while(low<=high){\n int mid=(low+high)/2;\n\t\t\t//mid represent the task and we are finding if he can complete mid task or not\n // System.out.println("midd "+mid);\n int wc[]=Arrays.copyOf(workers,workers.length);\n int tc[]=Arrays.copyOf(tasks,tasks.length);\n if(canThisMuchTaskBeDone(mid,wc,tc,pills,strength)){\n low=mid+1; \n ans=mid;\n } \n else{\n high=mid-1;\n }\n }\n return ans;\n }\n}\n```
2
0
['Greedy', 'Binary Tree']
1
maximum-number-of-tasks-you-can-assign
[golang] binary search + greedy check
golang-binary-search-greedy-check-by-kee-h34c
\nfunc maxTaskAssign(tasks []int, workers []int, pills int, strength int) int {\n sort.Ints(tasks)\n sort.Ints(workers)\n\n l, h := 0, min(len(tasks),
keemzen
NORMAL
2021-11-16T23:15:58.983901+00:00
2021-11-16T23:15:58.983929+00:00
231
false
```\nfunc maxTaskAssign(tasks []int, workers []int, pills int, strength int) int {\n sort.Ints(tasks)\n sort.Ints(workers)\n\n l, h := 0, min(len(tasks), len(workers))\n for l <= h {\n m := (l + h) / 2\n if check(tasks[0:m], workers[len(workers)-m:], pills, strength) {\n l = m + 1\n } else {\n h = m - 1\n }\n }\n return l-1\n}\n\nfunc check(tasks, workers []int, pills, strength int) bool {\n n := len(tasks)\n used := make([]bool, n)\n availableTasks := newDeque(n) // tasks that can be done by current worker (some may require using pill)\n\n for workerIdx, taskIdx, maxTaskIdx := 0, 0, 0; workerIdx < n; workerIdx++ {\n // skip done tasks\n for ; used[taskIdx]; taskIdx++ {\n }\n\n // update queue of available tasks\n for ; maxTaskIdx < n && workers[workerIdx] + strength >= tasks[maxTaskIdx]; maxTaskIdx++ {\n availableTasks.pushBack(maxTaskIdx)\n }\n for !availableTasks.empty() && availableTasks.front() < taskIdx {\n availableTasks.popFront()\n }\n\n // do the easiest available task or use pill and do the hardest available one\n if workers[workerIdx] >= tasks[taskIdx] {\n used[taskIdx] = true\n } else {\n if pills == 0 || availableTasks.empty() {\n return false\n }\n pills--\n used[availableTasks.back()] = true\n availableTasks.popBack()\n }\n }\n return true\n}\n\nfunc min(i, j int) int {\n if i < j {\n return i\n }\n return j\n}\n```\n\nAnd finally my rather ugly deque implementation:\n```\ntype deque struct {\n values []int\n frontCur int\n backCur int\n}\n\nfunc newDeque(maxSize int) *deque {\n return &deque{\n values: make([]int, maxSize),\n frontCur: 0,\n backCur: -1,\n }\n}\n\nfunc (d *deque) front() int {\n return d.values[d.frontCur]\n}\n\nfunc (d *deque) popFront() {\n d.frontCur++\n}\n\nfunc (d *deque) back() int {\n return d.values[d.backCur]\n}\n\nfunc (d *deque) pushBack(x int) {\n d.backCur++\n d.values[d.backCur] = x\n}\n\nfunc (d *deque) popBack() {\n d.backCur--\n}\n\nfunc (d deque) empty() bool {\n return d.frontCur > d.backCur\n}\n```
2
0
['Binary Search', 'Go']
2
maximum-number-of-tasks-you-can-assign
nlgn Greedy Solution (can pass all tests but i'm not sure it's correct)
nlgn-greedy-solution-can-pass-all-tests-0v5ux
\n public int maxTaskAssign(int[] tasks, int[] workers, int pills, int strength) {\n Arrays.sort(tasks);\n Arrays.sort(workers);\n boole
nervose
NORMAL
2021-11-14T09:43:38.952906+00:00
2021-11-14T10:08:07.731932+00:00
428
false
```\n public int maxTaskAssign(int[] tasks, int[] workers, int pills, int strength) {\n Arrays.sort(tasks);\n Arrays.sort(workers);\n boolean[]usedWorkerInFirstRound=new boolean[workers.length];\n int maxPossibleUsedTaskLen=Math.min(tasks.length,workers.length);\n int curToJudgeWorkIndex=0;\n for(int i=0;i<maxPossibleUsedTaskLen;i++){\n while (curToJudgeWorkIndex<workers.length&&workers[curToJudgeWorkIndex]<tasks[i]){\n curToJudgeWorkIndex++;\n }\n if(curToJudgeWorkIndex==workers.length){\n break;\n }\n usedWorkerInFirstRound[curToJudgeWorkIndex]=true;\n curToJudgeWorkIndex++;\n }\n for (int i=workers.length-1;i>=0;i--){\n if(pills==0){\n break;\n }\n if(!usedWorkerInFirstRound[i]){\n workers[i]+=strength;\n pills--;\n }\n }\n for (int i=workers.length-1;i>=0;i--){\n if(pills==0){\n break;\n }\n if(usedWorkerInFirstRound[i]){\n workers[i]+=strength;\n pills--;\n }\n }\n Arrays.sort(workers);\n int res=0;\n curToJudgeWorkIndex=0;\n for(int i=0;i<maxPossibleUsedTaskLen;i++){\n while (curToJudgeWorkIndex<workers.length&&workers[curToJudgeWorkIndex]<tasks[i]){\n curToJudgeWorkIndex++;\n }\n if(curToJudgeWorkIndex==workers.length){\n break;\n }\n res++;\n curToJudgeWorkIndex++;\n }\n return res;\n }\n```
2
0
['Greedy', 'Java']
1
maximum-number-of-tasks-you-can-assign
(C++) 2071. Maximum Number of Tasks You Can Assign
c-2071-maximum-number-of-tasks-you-can-a-ufh3
\n\nclass Solution {\npublic:\n int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills, int strength) {\n sort(tasks.begin(), tasks.end
qeetcode
NORMAL
2021-11-13T23:28:21.768299+00:00
2021-11-13T23:28:21.768327+00:00
521
false
\n```\nclass Solution {\npublic:\n int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills, int strength) {\n sort(tasks.begin(), tasks.end()); \n sort(workers.begin(), workers.end()); \n \n auto fn = [&](int k) {\n int p = pills; \n multiset<int> st(workers.end()-k, workers.end()); \n for (int i = k-1; i >= 0; --i) {\n int task = tasks[i]; \n if (task <= *(st.rbegin())) st.erase(prev(st.end())); \n else if (task <= *st.rbegin() + strength && p) {\n --p; \n auto it = st.lower_bound(task - strength); \n st.erase(it); \n } \n else return false; \n }\n return true; \n }; \n \n int lo = 0, hi = min((int)tasks.size(), (int)workers.size()); \n while (lo < hi) {\n int mid = lo + (hi - lo + 1)/2; \n if (fn(mid)) lo = mid; \n else hi = mid - 1; \n }\n return lo; \n }\n};\n```
2
0
['C']
1
maximum-number-of-tasks-you-can-assign
[C++] 132 ms/100%, O((n+m) * log(min(n, m)) ), no multiset.
c-132-ms100-onm-logminn-m-no-multiset-by-8nbg
Main ideas are the same as in solutions with multiset (upgraded with a final idea of 3 pointers+deque).\n\n\nstatic const int __ = []() { std::ios::sync_with_st
a_le_k
NORMAL
2021-11-13T16:47:17.234232+00:00
2021-11-13T18:08:37.866353+00:00
390
false
Main ideas are the same as in solutions with multiset (upgraded with a final idea of 3 pointers+deque).\n\n```\nstatic const int __ = []() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); return 0; }();\n\nconstexpr int MX=50\'000;\nbool used[MX];\n\nstruct array_deque\n{\n int vals[MX];\n int posL, posR;\n \n void reset() { posL=posR=0; }\n int& front() { return vals[posL]; }\n int& back() { return vals[posR-1]; }\n void pop_front() { posL++; }\n void pop_back() { posR--; }\n void push_back(int x) { vals[posR++]=x; }\n bool empty() { return posL>=posR; }\n};\narray_deque good_positions;\n\nclass Solution {\n vector<int> T, W;\n int D, P, n, m;\n \n bool ok(int X)\n {\n memset(used, false, X);\n int p=P;\n //deque<int> good_positions;\n good_positions.reset();\n \n for(int j1=0, j2=0, i=0; i<X; i++)\n {\n while(j2<X && T[j2]<=W[m-X+i]+D) good_positions.push_back(j2++);\n \n while(j1<X && used[j1]) j1++;\n assert(j1<X);\n \n if(T[j1]<=W[m-X+i])\n {\n while(!good_positions.empty() && j1>=good_positions.front()) good_positions.pop_front();\n \n used[j1]=true;\n j1++;\n continue;\n }\n \n if(good_positions.empty()) return false;\n p--;\n if(p<0) return false;\n \n int idx=good_positions.back(); good_positions.pop_back();\n used[idx]=true;\n }\n return true;\n }\n \npublic:\n int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills, int strength) {\n T=move(tasks), W=move(workers);\n n=T.size(), m=W.size();\n P=pills, D=strength;\n\n int LEN=min(n, m);\n \n //sort(T.begin(), T.end());\n //sort(W.begin(), W.end());\n nth_element(T.begin(), T.begin()+LEN, T.end());\n nth_element(W.begin(), W.end()-LEN, W.begin());\n sort(T.begin(), T.begin()+LEN);\n sort(W.end()-LEN, W.end());\n \n int L=0, R=LEN;\n while(L<R)\n {\n int M=(L+R+1)/2;\n \n if(ok(M)) L=M;\n else R=M-1;\n }\n assert(L==R);\n return L;\n }\n};\n```
2
2
[]
2
maximum-number-of-tasks-you-can-assign
Java Binary Search + TreeMap Solution with comments
java-binary-search-treemap-solution-with-qyt9
So if you want to find maximum number of tasks that can be completed with given sets of workers, tasks and pills we can divide the problem in following way \n\n
pathey
NORMAL
2024-11-18T19:22:30.032516+00:00
2024-11-18T19:22:30.032539+00:00
170
false
So if you want to find maximum number of tasks that can be completed with given sets of workers, tasks and pills we can divide the problem in following way \n\n1) First if we are given n (The maximum number of tasks we can finish can we check if it possible to finish n tasks with workers & pills)\n2) If we can efficiently check for any given n we can apply binary search to find the maximum value of n.\n\nFirst sort the tasks & workers array.\n\nNow in order to check if n tasks can be finished or not first step is to select which n tasks we want to finish & which n workers will finish those tasks. We can always take tasks which require least strength, so first n tasks and we can take workers with most strength so last n workers. \n\nOnce we have selected tasks and workers now we have to see if workers can finish those tasks or not now checking part is a little tricky one first will take the worker with least strength & try to assign the smallest tasks to the worker now here two cases are possible\n\ncase 1) worker has enough strength to finish the task\ncase 2) worker does not have strength to finish the task\n\nFor case 1 we can simply move to next worker and next task\nFor case 2 we will have to give the worker a pill to increase the strength of the worker otherwise we won\'t be able to fullfill the number of tasks so if we have no pills left it is not possible to finish n tasks, Once worker has received the pill we will try to find the maximum strength task the worker can do out of all remaining tasks, We can use TreeMap to find such task with getFloorKey(x) function which will return largest key which is smaller or equal to x. And we will assign that task to the worker and move forward. If we reach till end we can complete n tasks so will return true\n\n\n```\nclass Solution {\n public int maxTaskAssign(int[] tasks, int[] workers, int pills, int strength) {\n Arrays.sort(tasks);\n Arrays.sort(workers);\n int low=0;\n int high=tasks.length;\n int ans=0;\n while(low<=high)\n {\n int mid=(low+high)/2;\n\t\t\t//Check if task assignment is possible\n if(isPossible(tasks,workers,pills,strength,mid))\n {\n ans=mid;\n low=mid+1;\n }else{\n high=mid-1;\n }\n }\n return ans;\n \n }\n \n public boolean isPossible(int tasks[],int workers[],int pills,int strength,int n)\n {\n if(Math.min(workers.length,tasks.length)<n)\n return false;\n TreeMap<Integer,Integer> tm=new TreeMap<>();\n\t\t\n\t\t//Will add smallest n tasks to treemap\n for(int i=0;i<n;i++)\n {\n tm.put(tasks[i],tm.getOrDefault(tasks[i],0)+1);\n }\n\t\t\n\t\t//Will take n workers with most strength\n for(int j=workers.length-n;j<workers.length;j++)\n {\n int smallest=tm.firstKey();\n if(workers[j]<smallest)\n {\n\t\t\t\t//case 2: worker can not finish the task without the pill\n if(pills==0)\n return false;\n pills--;\n if(tm.floorKey(workers[j]+strength)!=null)\n smallest=tm.floorKey(workers[j]+strength);\n else\n return false;\n \n }\n //smallest is the task which workers[j] can do\n if(tm.get(smallest)==1)\n tm.remove(smallest);\n else\n tm.put(smallest,tm.get(smallest)-1);\n }\n return true;\n }\n \n \n}\n```
1
0
['Tree', 'Binary Tree', 'Java']
0
maximum-number-of-tasks-you-can-assign
EASY SOLUTION || CLEAN CODE
easy-solution-clean-code-by-udittyagi07-nl7v
\n# Code\n\nclass Solution {\npublic:\n bool check(vector<int>& tasks, vector<int>& workers, int pills, int strength,int index)\n {\n multiset<int>
udittyagi07
NORMAL
2024-05-07T06:54:12.915605+00:00
2024-05-07T06:54:12.915640+00:00
166
false
\n# Code\n```\nclass Solution {\npublic:\n bool check(vector<int>& tasks, vector<int>& workers, int pills, int strength,int index)\n {\n multiset<int> st;\n for(auto it:workers)\n {\n st.insert(it);\n }\n for(int i=index-1;i>=0;i--)\n {\n auto it=st.lower_bound(tasks[i]);\n if(it!=st.end())\n {\n st.erase(it);\n }\n else\n {\n if(pills<=0)\n {\n return false;\n }\n else\n {\n it=st.lower_bound(tasks[i]-strength);\n if(it!=st.end())\n {\n st.erase(it);\n pills--;\n }\n else\n {\n return false;\n }\n }\n }\n }\n return true;\n }\n int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills, int strength) {\n sort(tasks.begin(),tasks.end());\n sort(workers.begin(),workers.end());\n int low=0;\n int high=min(workers.size(),tasks.size());\n while(low<high)\n {\n int mid=(low+high+1)/2;\n if(check(tasks,workers,pills,strength,mid)==true)\n {\n low=mid;\n }\n else\n {\n high=mid-1;\n }\n }\n return high;\n }\n};\n\n```
1
0
['C++']
1
maximum-number-of-tasks-you-can-assign
🔥🔥C++ | Intuition + Approach | multi set + Binary Search | Easy to understand🔥🔥
c-intuition-approach-multi-set-binary-se-9p11
Intuition\n\n1. We need to find an assignment where the maximum number of workers can be assigned tasks, potentially using pills to boost their strength if nece
keepcalmhgkm
NORMAL
2024-04-08T12:58:29.535441+00:00
2024-04-08T12:58:29.535470+00:00
130
false
# Intuition\n\n1. We need to find an assignment where the maximum number of workers can be assigned tasks, potentially using pills to boost their strength if necessary.\n2. A greedy approach might not be optimal as stronger workers might be better suited for higher-strength tasks even after using pills on weaker ones.\n\n# Approach\n1. Sorting: Sort both tasks and workers in ascending order. This ensures we consider the easiest tasks and strongest workers first for assignment.\n2. Binary Search: Perform a binary search on the range 1 (minimum number of workers) to min(workers.size(), tasks.size()) (maximum number of workers that can be assigned). For each value k (number of workers to consider):\n3. Use a helper function helper to check if k tasks can be completed with the available workers and pills.\n4. helper Function:\n - Use a multiset named wks to store the strengths of the remaining k strongest workers.\n - Iterate backward through the tasks (highest strength first):\n If the current task\'s strength is greater than the strongest worker\'s strength (*wks.rbegin()), and there are still pills available:\n - Reduce the task\'s required strength by the pill boost (t -= strength).\n - Decrement the pill count (pills--).\n - Try to find a worker in wks whose strength is sufficient for the current task using lower_bound. If no such worker exists (x == wks.end()), it means an assignment for this many tasks is not possible.\n - If a worker is found, remove them from wks (wks.erase(x)) as they are assigned to this task.\n - If all tasks up to index i can be assigned, return true, indicating it\'s possible to complete k tasks. Otherwise, return false.\n5. Binary Search Outcome:\nIf helper returns true for k workers, it means this is a feasible assignment. We update l (left pointer) to k to search for a potential higher number of tasks.\nOtherwise, helper returns false, indicating k workers are insufficient. We update r (right pointer) to k-1 to explore lower numbers of workers.\n\n# Complexity\n- Time Complexity: O(n * log(n)), where n is the number of tasks or workers (whichever is smaller). This is due to sorting (n log n) and the binary search loop with helper function calls (log n).\n- Space Complexity: O(n), for sorting both tasks and workers.\n\n# Code\n```\nclass Solution {\npublic:\n bool helper(vector<int>& tasks, vector<int>& workers, int pills, int strength, int k){\n if(k == 0) return true;\n multiset<int> wks(workers.end() - k, workers.end());\n for(int i = k-1; i >= 0; i--)\n {\n int t = tasks[i];\n if(tasks[i] > *wks.rbegin() and pills > 0)\n {\n t -= strength;\n pills--;\n }\n auto x = wks.lower_bound(t);\n if(x == wks.end()) return false;\n wks.erase(x);\n }\n return true;\n }\n int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills, int strength) {\n sort(workers.begin(), workers.end());\n sort(tasks.begin(), tasks.end());\n int l = 0, r = min(workers.size(), tasks.size());\n while(l < r)\n {\n int m = (l + r + 1)/2;\n if(helper(tasks, workers, pills, strength, m))\n {\n l = m;\n }\n else r = m-1;\n }\n return l;\n }\n // 2 - 3\n // 3\n};\n```
1
0
['Binary Search', 'Binary Search Tree', 'Ordered Map', 'Ordered Set', 'C++']
0
maximum-number-of-tasks-you-can-assign
JAVA Simple TreeMap and binarySerch Solution
java-simple-treemap-and-binaryserch-solu-oox0
```\nclass Solution {\n \n public int maxTaskAssign(int[] tasks, int[] workers, int pills, int strength) { \n Arrays.sort(tasks);\n Arrays
newton3010
NORMAL
2022-02-26T07:46:15.273882+00:00
2022-02-26T07:46:15.273912+00:00
587
false
```\nclass Solution {\n \n public int maxTaskAssign(int[] tasks, int[] workers, int pills, int strength) { \n Arrays.sort(tasks);\n Arrays.sort(workers);\n \n int st = 0;\n int end = Math.min(tasks.length, workers.length)-1;\n int ans =0;\n while(st<=end){\n int mid = (st+end)/2;\n if(isPossible(tasks, workers, pills, strength, mid)){\n st = mid+1;\n ans = Math.max(ans, mid+1);\n }else{\n end = mid-1;\n }\n }\n return ans;\n }\n \nboolean isPossibleToComplete(int[] tasks, int[] workers, int pills, int strength, int mid) {\n int n = workers.length;\n TreeMap<Integer, Integer> map = new TreeMap<>();\n \n for (int i = n - 1, count = 0; count <= mid && i >= 0; i--, count++) {\n map.merge(workers[i], 1, (a, b) -> a + b);\n }\n int done = n - 1;\n int count = mid;\n for (int i = mid; i >= 0; i--) {\n int val = tasks[i];\n Integer kv = map.ceilingKey(val);\n if (kv != null) {\n updateMap(map, kv);\n } else {\n if(pills>0){\n int newStrg = val-strength;\n Integer newKv = map.ceilingKey(newStrg);\n if(newKv!=null){\n updateMap(map, newKv);\n pills--;\n }else {\n return false;\n }\n } else {\n return false;\n }\n }\n }\n return true;\n }\n void updateMap(TreeMap<Integer, Integer> map, int key){\n int vl = map.get(key);\n map.put(key, vl - 1);\n if (vl - 1 == 0) {\n map.remove(key);\n }\n }\n}\n
1
0
['Tree', 'Java']
0
maximum-number-of-tasks-you-can-assign
[JavaScript | JS] BinarySearch
javascript-js-binarysearch-by-wwwap-tn62
\n\njs\n/**\n * @param {number[]} tasks\n * @param {number[]} workers\n * @param {number} pills\n * @param {number} strength\n * @return {number}\n */\nconst ma
wwwap
NORMAL
2021-11-30T03:31:17.880530+00:00
2021-11-30T03:31:17.880576+00:00
221
false
\n\n```js\n/**\n * @param {number[]} tasks\n * @param {number[]} workers\n * @param {number} pills\n * @param {number} strength\n * @return {number}\n */\nconst maxTaskAssign = function(tasks, workers, pills, strength) {\n tasks.sort((a, b) => a - b)\n workers.sort((a, b) => b - a)\n const m = tasks.length, n = workers.length\n const { min, floor } = Math\n let l = 0, r = min(n, m)\n while (l < r) {\n const mid = r - floor((r - l) / 2)\n if (check(mid)) l = mid\n else r = mid - 1\n }\n\n return l\n\n function check(k){\n const wArr = workers.slice(0, k), tArr = tasks.slice(0, k)\n let tries = pills, bs = new Bisect()\n wArr.reverse()\n tArr.reverse()\n \n for (let elem of tArr) {\n const place = bs.bisect_left(wArr, elem)\n if (place < wArr.length) {\n wArr.pop()\n } else if (tries > 0) {\n const place2 = bs.bisect_left(wArr, elem - strength)\n if (place2 < wArr.length) {\n wArr.splice(place2, 1)\n tries -= 1\n }\n } else return false\n }\n \n return wArr.length === 0\n }\n};\n\n////////////////Template////////////////\nfunction Bisect() {\n return { insort_right, insort_left, bisect_left, bisect_right }\n function insort_right(a, x, lo = 0, hi = null) {\n lo = bisect_right(a, x, lo, hi)\n a.splice(lo, 0, x)\n }\n function bisect_right(a, x, lo = 0, hi = null) {\n // > upper_bound\n if (lo < 0) throw new Error(\'lo must be non-negative\')\n if (hi == null) hi = a.length\n while (lo < hi) {\n let mid = parseInt((lo + hi) / 2)\n x < a[mid] ? (hi = mid) : (lo = mid + 1)\n }\n return lo\n }\n function insort_left(a, x, lo = 0, hi = null) {\n lo = bisect_left(a, x, lo, hi)\n a.splice(lo, 0, x)\n }\n function bisect_left(a, x, lo = 0, hi = null) {\n // >= lower_bound\n if (lo < 0) throw new Error(\'lo must be non-negative\')\n if (hi == null) hi = a.length\n while (lo < hi) {\n let mid = parseInt((lo + hi) / 2)\n a[mid] < x ? (lo = mid + 1) : (hi = mid)\n }\n return lo\n }\n}\n```
1
0
['Binary Tree', 'JavaScript']
0
maximum-number-of-tasks-you-can-assign
Simple explaination using binary search + greedy
simple-explaination-using-binary-search-5dpf2
\nclass Solution {\npublic:\n bool can_do_m_tasks(int m,vector<int> &tasks,vector<int> &workers,int pills,int strength)\n {\n multiset<int> ms;\n
deepak_ky
NORMAL
2021-11-29T14:15:06.135741+00:00
2021-11-29T14:15:06.135773+00:00
377
false
```\nclass Solution {\npublic:\n bool can_do_m_tasks(int m,vector<int> &tasks,vector<int> &workers,int pills,int strength)\n {\n multiset<int> ms;\n for(auto x : workers)\n {\n ms.insert(x);\n }\n \n //I I want to check If I complete m tasks, \n //I will try to complete the easiest m tasks\n \n //And In those m tasks also , I will try to complete the hardest first\n //So that big values do not get used up for small values\n \n // Consider m = 3;\n // tasks : 1 , 2 ,3\n // workers : 0 , 3 , 3\n \n // If I start with tasks[0] it would be completed by worker[1] without any pills\n // then tasks[1] would be completed by worker[2] without any pills\n // and then tasks[2] cannot be completed by worker[0] with the help of any pills also\n \n //therefore If I satisfy tasks[2] with workers[2] , task[1] with workers[1],\n //and tasks[0] with worker[0] with the help of pills.\n \n \n for(int i=m-1;i>=0;i--)\n {\n //First I will try to check If I can do it without the help of any pills\n auto it = ms.lower_bound(tasks[i]);\n if(it == ms.end())\n {\n //Now I will check can I do check If I can do it with the help of pills\n \n //If there are no pills remaining return false\n if(pills == 0)\n {\n return false;\n }\n else\n {\n auto it1 = ms.lower_bound(tasks[i]-strength);\n \n if(it1 == ms.end())\n {\n return false;\n }\n else \n {\n ms.erase(it1);\n pills--;\n }\n }\n }\n else\n {\n ms.erase(it);\n }\n }\n \n return true;\n \n \n }\n int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills, int strength) \n {\n int t = tasks.size();\n int w = workers.size();\n \n sort(tasks.begin(),tasks.end());\n sort(workers.begin(),workers.end());\n \n int l = 0;\n int h = min(t,w);\n int ans = 0;\n \n while(l <= h)\n {\n int m = l + ((h-l)/2);\n if(can_do_m_tasks(m,tasks,workers,pills,strength))\n {\n ans = m;\n l = m + 1;\n }\n else h = m - 1;\n }\n \n return ans;\n \n }\n};\n```\n\nPlease upvote
1
1
['Greedy', 'C', 'Binary Tree']
0
maximum-number-of-tasks-you-can-assign
JAVA | Greedy | O(n*logn*logn)
java-greedy-onlognlogn-by-dakshbhabra-e1zv
\n\nclass Solution {\n public int maxTaskAssign(int[] t, int[] w, int p, int s) {\n int n = w.length;\n int m = t.length;\n Arrays.sort(
dakshbhabra
NORMAL
2021-11-28T18:56:36.359356+00:00
2021-11-28T18:57:20.824723+00:00
558
false
\n```\nclass Solution {\n public int maxTaskAssign(int[] t, int[] w, int p, int s) {\n int n = w.length;\n int m = t.length;\n Arrays.sort(t);\n \n int lo = 1, hi = Math.min(n, m); // hi = Math.min(n, m), since max tasks you can assign is the minimum of tasks and workers\n int ans = 0;\n\t\t// binary search to find the max tasks we can assign\n while(lo <= hi){\n int mid = (lo+hi)>>1;\n if(check(t, w, p, s, mid)){ \n ans = mid;\n lo = mid+1;\n }else{\n hi = mid-1;\n }\n }\n return ans;\n }\n \n boolean check(int []t, int w[], int p, int s, int n){\n int idx = n-1;\n TreeMap<Integer, Integer> map = new TreeMap<>();\n addAll(w, map);\n \n while(idx >= 0){\n Integer strongest = map.ceilingKey(t[idx]); // try assigning the task to the strongest worker\n if(strongest == null){\n if(p == 0) return false;\n Integer weekest = map.ceilingKey(t[idx]-s); // try assigning the task to the weekest worker with pill\n if(weekest == null) return false; // if cannot assign the task return false\n remove(map, weekest);\n p--;\n }else{\n remove(map, strongest);\n }\n idx--;\n }\n return true; // if all k tasks are assigned then return true\n }\n \n void addAll(int[] w, TreeMap<Integer, Integer> map){\n for(int i: w) map.put(i, map.getOrDefault(i, 0) + 1);\n }\n \n void remove(TreeMap<Integer, Integer> map, int val){\n if(map.get(val) == 1) map.remove(val);\n else map.put(val, map.get(val)-1);\n }\n}\n```
1
0
['Greedy', 'Tree', 'Java']
1
maximum-number-of-tasks-you-can-assign
[C++] Binary Search, O(NlgN) using std::list
c-binary-search-onlgn-using-stdlist-by-s-vxo7
O(NlgN) using std::list\n\nc++\nclass Solution {\npublic:\n int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills, int strength) {\n s
slo
NORMAL
2021-11-14T10:08:46.208558+00:00
2021-11-24T17:49:05.843093+00:00
276
false
# O(NlgN) using std::list\n\n```c++\nclass Solution {\npublic:\n int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills, int strength) {\n sort(begin(tasks), end(tasks));\n sort(begin(workers), end(workers));\n auto check = [&](int n) {\n list<int> S(end(workers) - n, end(workers));\n auto j = S.end(), i = j;\n int p = 0;\n while (n--) {\n if (p < pills) {\n while (i != S.begin() && *prev(i) + strength >= tasks[n]) --i;\n if (i != S.end() && *i + strength < tasks[n]) ++i;\n } else {\n i = S.end();\n }\n \n while (j != S.begin() && *prev(j) >= tasks[n]) --j;\n if (j != S.end() && *j < tasks[n]) ++j;\n \n if (i == S.end() && j == S.end()) return false;\n if (j != S.end()) {\n if (i == j) ++i;\n S.erase(j++);\n } else {\n ++p;\n if (j == i) ++j;\n S.erase(i++);\n }\n }\n return true;\n };\n int L = 0, R = min(workers.size(), tasks.size()) + 1;\n while (L + 1 < R) {\n int MID = (L + R) >> 1;\n if (check(MID)) L = MID;\n else R = MID;\n }\n return L;\n }\n};\n```\n\n# O(NlgNlgN) using std::multiset\n```c++\nclass Solution {\npublic:\n int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills, int strength) {\n sort(begin(tasks), end(tasks));\n sort(begin(workers), end(workers));\n auto check = [&](int n) {\n multiset<int> S(end(workers) - n, end(workers));\n int p = 0;\n while (n--) {\n auto i = p < pills ? S.lower_bound(tasks[n] - strength) : S.end();\n auto j = S.lower_bound(tasks[n]);\n if (i == S.end() && j == S.end()) return false;\n if (j != S.end()) {\n S.erase(j);\n } else {\n ++p;\n S.erase(i);\n }\n }\n return true;\n };\n int L = 0, R = min(workers.size(), tasks.size()) + 1;\n while (L + 1 < R) {\n int MID = (L + R) >> 1;\n if (check(MID)) L = MID;\n else R = MID;\n }\n return L;\n }\n};\n```
1
0
[]
1
maximum-number-of-tasks-you-can-assign
C++ Why is this TLE? Thanks
c-why-is-this-tle-thanks-by-robbinb1993-qugs
Came up with this binary search solution and greedy approach but kept hitting time limit during contest. Complexity is O(N (log N)^2). What is wrong with it? Th
robbinb1993
NORMAL
2021-11-13T16:22:25.856315+00:00
2021-11-13T16:39:40.545142+00:00
340
false
Came up with this binary search solution and greedy approach but kept hitting time limit during contest. Complexity is O(N (log N)^2). What is wrong with it? Thanks.\n\n```\nclass Solution {\npublic:\n bool possible(const int M, vector<int>& tasks, vector<int>& workers, int pills, int strength) {\n \n if (M + 1 > workers.size())\n return false;\n \n multiset<int> S;\n\n for (auto& w : workers)\n S.insert(w);\n \n for (int i = M; i >= 0; i--) {\n if (S.empty())\n return false;\n \n auto worker = lower_bound(S.begin(), S.end(), tasks[i]);\n if (worker == S.end()) {\n worker = lower_bound(S.begin(), S.end(), tasks[i] - strength);\n if (worker == S.end())\n return false;\n pills--;\n if (pills < 0)\n return false; \n }\n S.erase(worker);\n }\n return true; \n }\n \n \n \n int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills, int strength) {\n int L = 0;\n int R = int(tasks.size()) - 1;\n int ans = -1;\n \n sort(tasks.begin(), tasks.end());\n \n while (L <= R) {\n int M = (R + L) / 2;\n if (possible(M, tasks, workers, pills, strength)) {\n ans = M;\n L = M + 1;\n }\n else {\n R = M - 1;\n }\n }\n \n return ans + 1;\n }\n};\n```\n\nFound the cause......\n\nlower_bound(S.begin(), S.end(), tasks[i]) is actually O(N) and S.lower_bound(tasks[i]) is O(log N). Man oh man! This cost me a good ranking position. It just got accepted after this tiny change ;)
1
0
[]
5
maximum-number-of-tasks-you-can-assign
cpp greedy using bserach
cpp-greedy-using-bserach-by-hareeshghk-5e39
IntuitionApproachComplexity Time complexity: O(log N * (M+N) * log M) Space complexity: O(M) for multisetCode
hareeshghk
NORMAL
2025-03-29T19:09:34.421507+00:00
2025-03-29T19:09:34.421507+00:00
39
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)$$ --> O(log N * (M+N) * log M) - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> O(M) for multiset # Code ```cpp [] class Solution { int s; vector<int> ts, ws; public: int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills, int strength) { // O(N log N) sort(tasks.begin(), tasks.end()); // O(M log M) sort(workers.begin(), workers.end()); int n = tasks.size(); int m = workers.size(); int left = 0; int right = min(n, m); int answer = 0; // O(log N * (M+N) * log M) while (left <= right) { // expected number of tasks to be completed. int mid = (left + right)/2; // (M * log M) multiset<int> workersSet(workers.end() - mid, workers.end()); int pillCountRemaining = pills; // O(N * log M) for (int i = mid-1; i>=0; --i) { auto it = prev(workersSet.end()); if (*it < tasks[i]) { if (pillCountRemaining == 0) break; it = workersSet.lower_bound(tasks[i] - strength); if (it == workersSet.end()) break; pillCountRemaining--; } workersSet.erase(it); } if (workersSet.empty()) { answer = mid; left = mid + 1; } else { right = mid - 1; } } return answer; } }; ```
0
0
['C++']
1
maximum-number-of-tasks-you-can-assign
Python Hard
python-hard-by-lucasschnee-no5l
null
lucasschnee
NORMAL
2025-01-17T19:51:26.928932+00:00
2025-01-17T19:51:26.928932+00:00
7
false
```python3 []from sortedcontainers import SortedList class Solution: def maxTaskAssign(self, tasks: List[int], workers: List[int], pills: int, strength: int) -> int: ''' we want to maximize the number of tasks selected we need to do this in nlogn or better binary search on whether or not we can satisfy all tasks <= x then remove all tasks <= x then remove the rest ''' N = len(tasks) W = len(workers) tasks.sort() workers.sort() def good(target) -> bool: ''' can we remove all tasks <= target ''' # can we remove all tasks with index <= target? ''' [4, 6, 6] [5, 5, 8] how do we know to order it: 4 6 6 8 5 5 then, we only have to apply strength once maybe, we resort the list? must be some type of O(n) dp the tricky part is whether or not we want to give the pill and whether we want to assign a task to a given worker for each task from greatest to smallest if task >= greatest worker we want to find smallest worker to get juiced to take on task ''' T = tasks[:target+1] sl = SortedList() if len(T) > W: return False z = W - 1 while z >= 0 and len(sl) < len(T): sl.add(workers[z]) z -= 1 if len(T) > len(sl): return False count = 0 for t in T[::-1]: if t <= sl[-1]: sl.pop(-1) continue else: count += 1 diff = t - strength index = sl.bisect_left(diff) if index == len(sl): return False sl.pop(index) return count <= pills # bs on best index l, r = 0, N - 1 best = -1 while l <= r: mid = (l + r) // 2 if good(mid): best = mid l = mid + 1 else: r = mid - 1 return best + 1 ```
0
0
['Python3']
0
maximum-number-of-tasks-you-can-assign
2071. Maximum Number of Tasks You Can Assign
2071-maximum-number-of-tasks-you-can-ass-4yxm
IntuitionApproachComplexity Time complexity: Space complexity: Code
G8xd0QPqTy
NORMAL
2025-01-17T15:58:48.978951+00:00
2025-01-17T15:58:48.978951+00:00
16
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 [] from sortedcontainers import SortedList class Solution: def maxTaskAssign(self, tasks, workers, pills, strength): tasks.sort() workers.sort() def can_assign(k): available_workers = SortedList(workers[-k:]) remaining_pills = pills for task in tasks[:k][::-1]: idx = available_workers.bisect_left(task) if idx < len(available_workers): available_workers.pop(idx) elif remaining_pills > 0: fallback_idx = available_workers.bisect_left(task - strength) if fallback_idx < len(available_workers): available_workers.pop(fallback_idx) remaining_pills -= 1 else: return False return len(available_workers) == 0 left, right = 0, min(len(workers), len(tasks)) + 1 while left + 1 < right: middle = (left + right) // 2 if can_assign(middle): left = middle else: right = middle return left ```
0
0
['Python3']
0
maximum-number-of-tasks-you-can-assign
maximum-number-of-tasks-you-can-assign- TS Solution
maximum-number-of-tasks-you-can-assign-t-rr14
\n# Code\ntypescript []\n/**\n * Maximize the number of tasks assigned to workers given their strength and the option to use pills.\n *\n * @param {number[]} ta
himashusharma
NORMAL
2024-11-12T07:06:56.499993+00:00
2024-11-12T07:06:56.500040+00:00
13
false
\n# Code\n```typescript []\n/**\n * Maximize the number of tasks assigned to workers given their strength and the option to use pills.\n *\n * @param {number[]} tasks - An array of tasks where each task has a specific strength requirement.\n * @param {number[]} workers - An array of workers where each worker has a specific strength.\n * @param {number} pills - The number of pills available to boost worker strength.\n * @param {number} strength - The amount by which a pill boosts a worker\'s strength.\n * @return {number} - The maximum number of tasks that can be assigned to workers.\n */\nconst maxTaskAssign = function(tasks: number[], workers: number[], pills: number, strength: number): number {\n // Sort tasks in ascending order and workers in descending order\n tasks.sort((a, b) => a - b);\n workers.sort((a, b) => b - a);\n\n const m = tasks.length, n = workers.length; // Get the number of tasks and workers\n const { min, floor } = Math; // Destructure some useful Math functions\n let l = 0, r = min(n, m); // Initialize left and right pointers for binary search\n\n while (l < r) {\n const mid = r - floor((r - l) / 2); // Calculate the middle index\n if (check(mid)) l = mid; // If we can assign mid tasks, move left\n else r = mid - 1; // Otherwise, adjust right boundary\n }\n\n return l; // Return the maximum number of tasks that can be assigned\n\n /**\n * Helper function to check if it\'s possible to assign k tasks.\n *\n * @param {number} k - The number of tasks to check for assignment.\n * @return {boolean} - True if tasks can be assigned, otherwise false.\n */\n function check(k: number): boolean {\n const wArr = workers.slice(0, k); // Get the strongest k workers\n const tArr = tasks.slice(0, k); // Get the k weakest tasks\n let tries = pills; // Initialize remaining pills\n const bs = Bisect(); // Create a new instance of the Bisect helper class\n wArr.reverse(); // Reverse workers to prioritize the strongest\n tArr.reverse(); // Reverse tasks to prioritize the weakest\n\n // Iterate over tasks to attempt assignment\n for (let elem of tArr) {\n const place = bs.bisect_left(wArr, elem); // Find a worker for the current task\n\n // If a worker can handle the task without a pill\n if (place < wArr.length) {\n wArr.pop(); // Assign the worker to the task\n } else if (tries > 0) { // If no worker can handle it and we have pills left\n const place2 = bs.bisect_left(wArr, elem - strength); // Check if a worker can handle it with a pill\n if (place2 < wArr.length) {\n wArr.splice(place2, 1); // Assign the worker who can do the task with a pill\n tries -= 1; // Use a pill\n }\n } else {\n return false; // No assignment possible\n }\n }\n\n return wArr.length === 0; // Return true if all tasks are assigned\n }\n};\n\n// Helper class for binary search operations\nfunction Bisect() {\n return { insort_right, insort_left, bisect_left, bisect_right };\n\n function insort_right(a: number[], x: number, lo: number = 0, hi: number | null = null): void {\n lo = bisect_right(a, x, lo, hi); // Get the position to insert\n a.splice(lo, 0, x); // Insert the element at the correct position\n }\n\n function bisect_right(a: number[], x: number, lo: number = 0, hi: number | null = null): number {\n // > upper_bound\n if (lo < 0) throw new Error(\'lo must be non-negative\');\n if (hi == null) hi = a.length; // Set hi to the length of the array if not provided\n while (lo < hi) {\n let mid = Math.floor((lo + hi) / 2); // Calculate mid index\n x < a[mid] ? (hi = mid) : (lo = mid + 1); // Adjust lo and hi based on comparison\n }\n return lo; // Return the position for the insertion\n }\n\n function insort_left(a: number[], x: number, lo: number = 0, hi: number | null = null): void {\n lo = bisect_left(a, x, lo, hi); // Get the position to insert\n a.splice(lo, 0, x); // Insert the element at the correct position\n }\n\n function bisect_left(a: number[], x: number, lo: number = 0, hi: number | null = null): number {\n // >= lower_bound\n if (lo < 0) throw new Error(\'lo must be non-negative\');\n if (hi == null) hi = a.length; // Set hi to the length of the array if not provided\n while (lo < hi) {\n let mid = Math.floor((lo + hi) / 2); // Calculate mid index\n a[mid] < x ? (lo = mid + 1) : (hi = mid); // Adjust lo and hi based on comparison\n }\n return lo; // Return the position for the insertion\n }\n}\n```
0
0
['Array', 'Binary Search', 'Greedy', 'Queue', 'Sorting', 'Monotonic Queue', 'TypeScript', 'JavaScript']
0
maximum-number-of-tasks-you-can-assign
Golang | 26ms | Binary Search | Dequeue
golang-26ms-binary-search-dequeue-by-har-ly45
golang []\npackage main\n\nimport (\n\t"sort"\n)\n\nfunc maxTaskAssign(tasks []int, workers []int, pills int, strength int) int {\n\tsort.Ints(tasks)\n\tsort.In
harshawasthi90
NORMAL
2024-11-07T20:20:38.115715+00:00
2024-11-12T07:32:04.500123+00:00
15
false
```golang []\npackage main\n\nimport (\n\t"sort"\n)\n\nfunc maxTaskAssign(tasks []int, workers []int, pills int, strength int) int {\n\tsort.Ints(tasks)\n\tsort.Ints(workers)\n\n\tl := 0\n\tr := min(len(tasks), len(workers))\n\n\tfor l < r {\n\t\tm := (l + r + 1) / 2\n\t\tif ok(tasks[:m], workers[len(workers)-m:], pills, strength) {\n\t\t\tl = m\n\t\t} else {\n\t\t\tr = m - 1\n\t\t}\n\t}\n\treturn l\n}\n\nfunc ok(tasks []int, workers []int, pills int, strength int) bool {\n\tti := 0\n\tqueue := NewDequeue()\n\n\tfor _, worker := range workers {\n\t\tfor ti < len(tasks) && worker+strength >= tasks[ti] {\n\t\t\tqueue.AddLast(tasks[ti])\n\t\t\tti++\n\t\t}\n\n\t\tif queue.Empty() {\n\t\t\treturn false\n\t\t}\n\n\t\tif queue.First() <= worker {\n\t\t\tqueue.RemoveFirst()\n\t\t} else if pills > 0 && queue.Last() <= worker+strength {\n\t\t\tqueue.RemoveLast()\n\t\t\tpills--\n\t\t} else {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\n// Dequeue Impl\nvar array [5e4 + 1]int\n\ntype Dequeue struct {\n\tstart int\n\tend int\n}\n\nfunc NewDequeue() *Dequeue {\n\treturn &Dequeue{start: 0, end: -1}\n}\n\nfunc (q *Dequeue) First() int {\n\treturn array[q.start]\n}\n\nfunc (q *Dequeue) Last() int {\n\treturn array[q.end]\n}\n\nfunc (q *Dequeue) RemoveFirst() {\n\tq.start++\n}\n\nfunc (q *Dequeue) RemoveLast() {\n\tq.end--\n}\n\nfunc (q *Dequeue) AddLast(val int) {\n\tq.end++\n\tarray[q.end] = val\n}\n\nfunc (q *Dequeue) Empty() bool {\n\treturn q.start > q.end\n}\n\n```
0
0
['Go']
0
maximum-number-of-tasks-you-can-assign
Beautiful question || C++ || Binary search || Pure greedy won't work
beautiful-question-c-binary-search-pure-z89f3
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
garvit_17
NORMAL
2024-11-05T22:41:56.845227+00:00
2024-11-05T22:41:56.845258+00:00
34
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 maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills,\n int strength) {\n sort(tasks.begin(), tasks.end());\n sort(workers.begin(), workers.end());\n int l=0,r=min(workers.size(),tasks.size());\n int ans = 0,temp=pills;\n while(l<=r)\n {\n int m=(l+r)/2;\n multiset<int>st(workers.end()-m,workers.end());\n int f=0;\n pills=temp;\n for(int i=m-1;i>=0;i--){\n auto it=st.lower_bound(tasks[i]);\n if(it!=st.end()){\n st.erase(it);\n }else{\n if(pills<=0){\n f=1;\n break;\n }\n else{\n auto it1=st.lower_bound(tasks[i]-strength);\n if(it1!=st.end()){\n pills--;\n st.erase(it1);\n }\n else{\n f=1;\n break; \n }\n }\n }\n }\n if(f==0)\n {\n ans=m;\n l=m+1;\n }\n else r=m-1;\n }\n return ans;\n }\n};\n```
0
0
['C++']
0
maximum-number-of-tasks-you-can-assign
Python 3: TC O(min(W,T)*log^2(min(W,T)), SC O(min(W,T)): Optimized Time Complexity
python-3-tc-ominwtlog2minwt-sc-ominwt-op-hdi0
Intuition\n\nThis solution is similar I think to the fastest ones, but offers better asymptotic complexity. Most solutions pop an intermediate index from a list
biggestchungus
NORMAL
2024-08-26T10:03:01.686225+00:00
2024-08-26T10:03:01.686250+00:00
7
false
# Intuition\n\nThis solution is similar I think to the fastest ones, but offers better asymptotic complexity. Most solutions pop an intermediate index from a list which takes `O(k)` time where `k <= min(W, T)`. There may be many pop operations so you wind up with `O(k**2)` time in binary search.\n\n**I found this problem VERY challenging.** I left my thought process in the code as comments - you can see where I tried a lot of things that didn\'t work before looking at the LC hints, then gradually figuring out what the pattern is and what we need to do.\n\n## Insight 1: Strongest Workers to Weakest Tasks\n\nThe basic idea behind this solution is **guess and check: see if we can assign `k` tasks in a reasonable time, then do binary search on `k`.**\n\nOur best chance of doing `k` tasks is to use the strongest `k` workers and the easiest `k` tasks. Using weaker workers or harder tasks will require at least as many pills and thus may not be possible for a given `pills` limit.\n\n## Insight 2: Cumulative Workers Above\n\nThe next insight is to realize that **we\'re looking for a bijection between workers and tasks after using pills.**\n\nThe main property we need from this bijection is that when we look at the tasks in order of difficulty ascending **if there are `t` tasks remaining then we need at least `t` workers with the current task\'s strength.**\n\nIn other words **we use counts of workers to avoid having to figure out exactly which task matches with which worker.**\n\n## Insight 3: Cumulative Counts from Deques and Heaps\n\nMy idea was this:\n* suppose our next task has difficulty `d` and there are `t` left\n* if there are at least `t` workers with strength `>= d` then we are good to proceed\n * **some of these workers are clean, i.e. not drugged (yet)**\n * **some of these workers are drugged with pills**\n* if there are fewer than `t` then we need to drug some of our workers\n * **we can\'t drug workers 2+ times, so we need a separate collection of drugged workers**\n * if there are enough clean workers below `d` that we can drug to be `>= d`, then put them in the collection of drugged workers\n * therefore **we also need need a collection of clean workers** \n\nSo the algorithm looks like this:\n1. while `drugged` is nonempty and the smallest element is less than the current task difficulty `d`, pop the smallest\n2. while `clean_above` is nonempty and the smallest element is less than `d`, move it to `clean_below` - the collection of workers we may need to drug later\n3. compare the total number of workers at least as strong as difficulty `d` to the number of remaining tasks `t`. The total works at least as strong are the lengths of `clean_above` and `drugged`\n4. if we don\'t have enough workers at least as strong, then we need to drug workers. If we need `pills_needed` workers then drug the `pils_needed` *strongest* workers in `clean_below`\n5. if we don\'t have enough workers to drug, or not enough pills, then we know `k` is impossible\n\n## Example\n\nHere\'s a tricky edge case that pushed my code to the limit and how it works in detail:\n\n```a\n\ntasks= 1857, 2301, 4236, 4710, 4777, 5079, 7276, 7581, 7896, 8656\nworkers= 557 772, 821, 1845, 2721, 2788, 3752, 4686, 4870\npills=2\nstrength = 2208\n\nk = 5 (match top 5 workers with bottom 5 tasks)\n\n d = 1857\n clean_above: 2721, 2788, 3752, 4686, 4870\n clean_below: empty\n drugged: empty\n\n 5 tasks left, 5 workers above: ok\n\n d = 2301\n clean_above: 2721, 2788, 3752, 4686, 4870\n clean_below: empty\n drugged: empty\n\n 4 tasks left, 5 workers above: ok\n\n d = 4236\n clean_above: 4686, 4870\n clean_below: 2721, 2788, 3752\n drugged: empty\n\n 3 tasks left, 2 workers above: need to drug a worker\n to get the best effect from our pill we drug the strongest\n worker below the current difficulty, maximizing how\n many difficulties it\'s relevant for\n\n promote 3752 to 3752 + 2208 = 5960\n \n d = 4710\n clean_above: 4870\n clean_below: 2721, 2788, 4686\n drugged: 5960\n\n 2 tasks left, 2 above (1 drugged, 1 clean): ok\n\n d = 4710\n clean_above: 4870\n clean_below: 2721, 2788, 4686\n drugged: 5960\n\n 2 tasks left, 2 above (1 drugged, 1 clean): ok\n\n d = 4777\n clean_above: 4870\n clean_below: 2721, 2788, 4686\n drugged: 5960\n\n 1 task left, 1 above (1 drugged, 1 clean): ok\n```\n\n## Compared to Other Solutions\n\nMost other solutions use a binary search to find the strongest worker weaker than the current difficulty (I think), then remove it from the middle of a list. This takes `O(k)` time, and `k` is `O(W, H)` which results in quadratic time complexity in the worst case.\n\nInstead this solution avoids popping from the middle of the heap by using more appropriate collections:\n* `clean_above` is a deque, workers is ordered so the deque is ascending as well\n * note that we could use a pointer into `workers` instead of having an explicit deque; this is easier to read though\n* `clean_below` is appended to in order of `clean_above`, which is ordered. We pop from the right which maintains this property. **Thus this solution lets us pop the strongest worker below the current difficulty in `O(1)`**\n* but the downside is that now we need a way to pop the weakest workers in `drugged` that are no longer above the current difficulty; I do this with a heap that requires `log(k)` time\n * popping from a list is `O(k)` so this is still a substantial improvement\n\n\n# Complexity\n- Time complexity: `O(min(W,T)*log^2(min(W,T)))`\n - the largest value of `k` is `min(W, T)` where we have `W` workers and `T` tasks\n - we do binary search on `k` hence one factor of `log(min(W,T))`\n - in each binary search iteration we see if `k` is possible, which involves iterating over `O(k)` tasks. In general we\'ll have to pop `O(k)` times from the `drugged` heap for `O(k log(k))` time, contributing the remainder of the complexity to leading order\n - other various things like `deque` creation, etc. are amortized `O(1)` per element and thus `O(k)` or cheaper\n\n- Space complexity: `O(min(W,T))`, the `deque`s and heap have at most `O(k)` elements in them\n\n# Code\n```python3 []\nclass Solution:\n def maxTaskAssign(self, tasks: List[int], workers: List[int], pills: int, strength: int) -> int:\n # HARD problem, tried a bunch of things but can\'t get something to work in linear or linearithmic time\n\n # T = len(tasks)\n # W = len(workers)\n # tasks.sort(reverse=True)\n # workers.sort(reverse=True)\n\n\n # key insight: suppose there\'s a task we could do with a worker and a pill\n # should we spend the pill? case A: If there\'s a later task the worker can do then maybe\n # case B: if there\'s no later task then definitely yes, otherwise the task will not be done\n #\n # each pill at most can let us accomplish 1 whole new task (it may take multiple pills per task)\n # so we can greedily spend 1 pill per task\n\n # let\'s return to case A:\n\n # we saw t1 > w1 >= t2\n #\n # if there\'s a later worker that can do t2 then pop that worker and do it\n #\n # if there\'s a later worker that needs a pill for \n #\n # t1 t2 t3 t4\n # w1 w2 w3\n\n # seems like a pending stack question, e.g. look at next worker and task\n # if worker can do it then assign and proceed\n # otherwise push both to stacks to form a "zipper" like t1,w1 t3,w3 as done above\n # at some point we\'ll end with an excess of tasks or an excess of workers\n\n # excess tasks: t1 t2 t3 t4\n # w1 w2\n # > spend no pills, each worker has a task\n\n # excess workers\n\n # t1 t2 t3\n # w1 w2 w3\n\n # if we can "zipper" numUnassignedTasks\n # then proceed\n\n # don\'t know, don\'t care, give up, there\'s a pattern or crazy clever insight I\'m missing and I\'m not going to find it at this point\n\n # or...\n # gap between tasks and workers doesn\'t matter\n # if curr worker is strong enough to handle next task, assign and move on\n # if curr worker is too weak even with a pill, discard task\n\n # will result in t1 t2 t3 t4 t5\n # w1 w2 w3 w4 w5\n #\n # skip remaining tasks\n #\n # if there is a pill for every worker at this point then spend that number of pills to gain one more task\n # otherwise tasks-1\n\n # except this fails on example 2 X(\n\n \n #### brute force, then optimize?\n\n # suppose we sort descending\n # then we want to know the max we can do of t: and w: with p pills left\n\n # @cache\n # def most(t: int, w: int, p: int):\n # if t == T or w == W: return 0\n\n # if workers[w] >= tasks[t]: return most(t+1, w+1, p)\n \n # best = most(t+1, w, p) # can always skip\n # if workers[w] + strength >= tasks[t]:\n # best = max(best, 1 + most(t+1, w+1, p-1)) # this seems strictly better\n\n\n #### HOLD UP A SECOND:\n # if we have t1 t2\n # w1 w2\n # if strength is big then we can spent one pill on w2 to fix w2, better than the zipper I was thinking of before!!!\n\n # so maybe the loop is\n # for each task:\n # find min remaining worker, if any, such that worker[w]+strength >= task\n # then assign\n # that will increase completed tasks\n\n # t1 t2\n # w1 w2\n\n\n\n ##### other idea\n # workers that can\'t be assigned to any task are useless\n\n # so maybe we sort ascending\n # and as we find workers we can\'t use, put them in a deque\n #\n # iter through tasks and workers in order\n #\n # w1 w2 w3 w4 w5\n # t1 t2\n #\n\n ##### trying again after a few hours\n\n # top-down DFS, then bottom-up DP with optimizations\n\n # t1 t2\n # w1 w2\n #\n # my algo says 2 pills needed for tw\n # but reality is we only need one pill, for w2 + strength > t1 and then w1 > t2\n\n # so the optimal matching is NOT in index order\n\n # want to maximize count of tasks "behind" workers after using pills\n #\n # so maybe for each task in order we try to find a worker without pills that can handle it\n # if not, then see if we can promote a worker with pills\n\n # problem: suppose we have\n # t1 t2 t3\n # w1 w2 w3 w4\n #\n # if we burn a pill on w1 then we get w1+p -- t1, and then w3--t2: 2 jobs\n # but best is w1--t1 w3--t2 w4+p--t3 for 3 jobs\n\n # what we need to do is look at cumulative workers with strength >= current job; if there\'s\n # not enough then using a pill will help\n # not enough, and using a pill helps: still might not be optimal\n #\n # t1 t2 t3 t4\n # w1 w2 w3\n #\n # t1: not enough workers left, so we\'d think promoting w1 with pill would help. But really w2 covers it\n # meanwhile w3 can\'t be promoted\n\n # without pills\n # for each task: assign to worker if possible, else ditch it\n\n ######## TIME FOR HINTS\n\n # 1. Is it possible to assign the first k smallest tasks to the workers?\n \n # for smallest task: is there a stronger worker?\n # for next smallest task: is there a next worker?\n # and so on, two-pointer\n\n # suppose we do that, but then we also keep track of workers we skipped along the way\n \n # then at each point we have to decide if we\'ll use a pill\n\n # t1 t2 t3 t4 t5 t6 t7\n # w1 w2 w3 w4 w5 w6 w7\n # * * * * *\n\n # 2. How can you efficiently try every k?\n\n # I just did the algo, it\'s a two-pointer...\n\n # Maybe 1. refers to using pills?\n\n # I think the point of 1. is that if we we can assign any k tasks it\'s going to be the lowest k\n\n ###### So how can we tell if we can do the first k with any number of pills?\n\n # IS IT GUESS AND CHECK???????\n\n # suppose we can do k\n # then there should be a bijection between workers and the lowest k tasks\n \n\n # how can we verify we can do k?\n\n # keep in mind nasty edge cases like this:\n # strength = 5\n #\n # tasks: 5 6 9\n # workers: 3 4 7 \n #\n #\n # right answer: promote 3 -> 8, 4 -> 9\n\n # idea is that we\'ll use top k workers and bottom k tasks, there will be a bijection\n #\n # for lowest task we need all k >= after using pills\n # \n\n # after much wrangling, tracking the numbers explicitly isn\'t working, too complicated, edge cases\n\n # can we something dumb like reduce the task cost by strength instead of increasing workers?\n # nope, same corner cases\n\n # last attept for tonight\n # track cumulative workers stronger than each task, including pills used\n\n # for the example above:\n # 5: 1 worker >=, so we need to spend 2 pills\n # promote 3 and 4 to 8 and 9\n #\n # now 5, expecting 3 tasks above, has 3. good\n #\n # 6: expects 2 >=, and we have three. good\n #\n # 9: expects 1 >=, and we have 1. good\n\n # in this way we don\'t track exactly what matches\n\n # in fact, this is an easier way to do the bookkeeping for tracking what we updated and when\n\n tasks.sort()\n workers.sort()\n\n T = len(tasks)\n W = len(workers)\n\n # print(f"{tasks=}\\n{workers=}\\n{pills=}")\n\n def possible(k: int) -> bool:\n p = pills\n clean_below = deque() # ascending values\n clean_above = deque(workers[-k:]) # ascending values\n drugged = [] # min heap of drugged workers\' strengths >= current task, heap b/c we push out of order potentially\n # print(f"{k=}")\n for t in range(k):\n while clean_above and clean_above[0] < tasks[t]:\n clean_below.append(clean_above.popleft())\n\n while clean_below and clean_below[0] + strength < tasks[t]: clean_below.popleft()\n\n while drugged and drugged[0] < tasks[t]: heappop(drugged)\n\n pills_needed = max(0, k - t - len(clean_above) - len(drugged)) # FIXED: max w/ 0 so p -= pills_needed doesn\'t ruin our results\n\n # print(f" {tasks[t]=}: {clean_above=}, {clean_below=}, {drugged=}, {pills_needed=}, {p=}")\n\n if pills_needed > p or pills_needed > len(clean_below): return False\n\n # we move from clean_below to drugged and append to drugged in order so drugged is always ordered\n p -= pills_needed\n for _ in range(pills_needed):\n # FIXED: do NOT popleft on clean below because the left, i.e. smallest, is the least flexible promotion\n # we want to increase cumulative workers to the right for as many elements as possible; we need to pop right/greatest\n # drugged.append(clean_below.popleft() + strength)\n heappush(drugged, clean_below.pop() + strength)\n\n return True\n\n lo = 0\n hi = min(W, T)\n while lo < hi:\n k = (lo + hi + 1)//2\n if possible(k):\n lo = k\n else:\n hi = k-1\n\n return hi\n```
0
0
['Python3']
0
maximum-number-of-tasks-you-can-assign
Binary search on answer + Greedy + Monotonic queue | Java faster than 100%
binary-search-on-answer-greedy-monotonic-1n4f
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
zephyryau
NORMAL
2024-08-13T01:22:45.007008+00:00
2024-08-13T01:22:45.007042+00:00
67
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(nlogn + mlogm)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\n int[] deque;\n\n public int maxTaskAssign(int[] tasks, int[] workers, int pills, int strength) {\n Arrays.sort(tasks);\n Arrays.sort(workers);\n int tsize = tasks.length;\n int wsize = workers.length;\n deque = new int[tsize];\n int max = 0;\n int left = 0;\n int right = Math.min(tsize, wsize);\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (check(tasks, workers, 0, mid - 1, wsize - mid, wsize - 1, pills, strength)) {\n max = mid;\n left = mid + 1;\n } else {\n right = mid - 1;\n }\n }\n return max;\n }\n\n private boolean check(int[] tasks, int[] workers, int tl, int tr, int wl, int wr, int pills, int strength) {\n int cnt = 0;\n int h = 0, t = 0;\n // i: worker\n // j : task\n for (int i = wl, j = tl; i <= wr; i++) {\n // how many task can be finished by current worker i, and store these tasks in monotonic queue\n while (j <= tr && tasks[j] <= workers[i]) {\n deque[t++] = j++;\n }\n // If there are tasks in queue, current worker (without pill) take the easiest one\n if (h < t && tasks[deque[h]] <= workers[i]) {\n h++;\n } else {\n // Worker cannot take any task without a pill, so store the tasks in monotonic queue that can be finished by current worker i with a pill\n while (j <= tr && tasks[j] <= workers[i] + strength) {\n deque[t++] = j++;\n }\n // Because worker has taken the pill, we need the worker to finish the hardest one in the queue so that the power of pill is used maximally (greedy)\n if (h < t) {\n cnt++;\n t--;\n } else {\n // If still cannot take any task even the worker has taken a pill, return false\n return false;\n }\n }\n }\n return cnt <= pills;\n }\n}\n```
0
0
['Java']
0
maximum-number-of-tasks-you-can-assign
This is an addition to a good solution
this-is-an-addition-to-a-good-solution-b-ku2z
Intuition\nPlease read this solution first, as I think it is pretty intuitive: https://leetcode.com/problems/maximum-number-of-tasks-you-can-assign/solutions/15
Fustigate
NORMAL
2024-06-28T13:22:34.311319+00:00
2024-06-28T13:22:34.311349+00:00
32
false
# Intuition\nPlease read this solution first, as I think it is pretty intuitive: https://leetcode.com/problems/maximum-number-of-tasks-you-can-assign/solutions/1575980/python-binary-search-check-answer-greedily/\n\nAfter that, use the code I provided below, which is a more efficient implementation of the solution at the link above, beating 95%.\n\nI don\'t take any credit for the solutions, this is what i found and wanted to share with those who need it, as I think these two are pretty well designed.\n\n# Code\n```python\nclass Solution:\n def maxTaskAssign(self, tasks: List[int], workers: List[int], pills: int, strength: int) -> int:\n if min(tasks) > max(workers) + (strength if pills > 0 else 0):\n return 0\n\n tasks.sort()\n workers.sort()\n\n def can_finish_n_tasks(n, pills):\n new_workers = workers[-n:] # most powerful n workers\n new_tasks = tasks[:n] # easiest n tasks\n task_idx = worker_idx = 0\n\n for _ in range(n):\n if new_tasks[task_idx] <= new_workers[worker_idx]:\n worker_idx += 1\n task_idx += 1\n continue\n new_strength = new_workers[worker_idx]+strength\n if pills > 0 and new_tasks[task_idx] <= new_strength:\n idx = bisect.bisect_right(new_tasks, new_strength)\n new_tasks.pop(idx-1)\n worker_idx += 1\n pills -= 1\n continue\n return False\n return True\n\n lo = 0\n hi = min(len(tasks), len(workers))\n while lo + 1 < hi:\n n = (lo+hi) // 2\n if can_finish_n_tasks(n, pills):\n lo = n\n else:\n hi = n\n if can_finish_n_tasks(hi, pills):\n return hi\n return lo\n```
0
0
['Binary Search', 'Python3']
0
maximum-number-of-tasks-you-can-assign
JS | Clean Code Binary Search + Queue
js-clean-code-binary-search-queue-by-nan-p9tp
Code\n\n/**\n * @param {number[]} tasks\n * @param {number[]} workers\n * @param {number} pills\n * @param {number} strength\n * @return {number}\n */\nvar maxT
nanlyn
NORMAL
2024-06-03T18:16:18.513956+00:00
2024-06-03T18:16:18.513975+00:00
10
false
# Code\n```\n/**\n * @param {number[]} tasks\n * @param {number[]} workers\n * @param {number} pills\n * @param {number} strength\n * @return {number}\n */\nvar maxTaskAssign = function (tasks, workers, pills, strength) {\n tasks.sort((a, b) => a - b);\n workers.sort((a, b) => b - a);\n\n const canCompleted = function (k) {\n let pillsLeft = pills;\n let queue = [];\n let j = 0;\n for (let i = k - 1; i >= 0; i--) {\n while (j < k && workers[i] + strength >= tasks[j]) {\n queue.push(tasks[j++]);\n }\n if (queue[0] <= workers[i]) {\n queue.shift();\n } else {\n if (pillsLeft === 0) {\n return false;\n } else {\n pillsLeft--;\n if (!queue.length) return false;\n queue.pop();\n }\n }\n }\n return true;\n }\n\n let left = 0;\n let right = Math.min(tasks.length, workers.length);\n while (left < right) {\n let mid = left + Math.floor((right - left) / 2) + 1;\n\n if (canCompleted(mid)) {\n left = mid;\n } else {\n right = mid - 1;\n }\n }\n\n return left;\n};\n```
0
0
['JavaScript']
0
maximum-number-of-tasks-you-can-assign
EASY SOLUTION || CLEAN CODE
easy-solution-clean-code-by-udittyagi07-yu6h
\n# Code\n\nclass Solution {\npublic:\n bool check(vector<int>& tasks, vector<int>& workers, int pills, int strength,int index)\n {\n multiset<int>
udittyagi07
NORMAL
2024-05-07T06:54:20.039118+00:00
2024-05-07T06:54:20.039148+00:00
84
false
\n# Code\n```\nclass Solution {\npublic:\n bool check(vector<int>& tasks, vector<int>& workers, int pills, int strength,int index)\n {\n multiset<int> st;\n for(auto it:workers)\n {\n st.insert(it);\n }\n for(int i=index-1;i>=0;i--)\n {\n auto it=st.lower_bound(tasks[i]);\n if(it!=st.end())\n {\n st.erase(it);\n }\n else\n {\n if(pills<=0)\n {\n return false;\n }\n else\n {\n it=st.lower_bound(tasks[i]-strength);\n if(it!=st.end())\n {\n st.erase(it);\n pills--;\n }\n else\n {\n return false;\n }\n }\n }\n }\n return true;\n }\n int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills, int strength) {\n sort(tasks.begin(),tasks.end());\n sort(workers.begin(),workers.end());\n int low=0;\n int high=min(workers.size(),tasks.size());\n while(low<high)\n {\n int mid=(low+high+1)/2;\n if(check(tasks,workers,pills,strength,mid)==true)\n {\n low=mid;\n }\n else\n {\n high=mid-1;\n }\n }\n return high;\n }\n};\n\n```
0
0
['C++']
0
maximum-number-of-tasks-you-can-assign
C++
c-by-user5976fh-iktq
\nclass Solution {\npublic:\n int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills, int strength) {\n int ans = 0, l = 0, r = tasks.s
user5976fh
NORMAL
2024-04-03T18:13:29.133995+00:00
2024-04-03T18:13:29.134030+00:00
0
false
```\nclass Solution {\npublic:\n int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills, int strength) {\n int ans = 0, l = 0, r = tasks.size();\n sort(tasks.begin(), tasks.end());\n while (l <= r){\n int m = (l + r) / 2;\n bool valid = true;\n int pillsLeft = pills;\n multiset<int> s(workers.begin(), workers.end());\n for (int i = m - 1; i >= 0; --i){\n if (!s.empty() && *prev(s.end()) >= tasks[i]){\n s.erase(prev(s.end()));\n }\n else{\n auto it = s.lower_bound(tasks[i] - strength);\n if (it == s.end() || --pillsLeft < 0){\n valid = false;\n break;\n }\n else{\n s.erase(it);\n }\n }\n }\n if (valid){\n ans = m;\n l = m + 1;\n }\n else r = m - 1;\n }\n return ans;\n }\n};\n```
0
0
[]
0
maximum-number-of-tasks-you-can-assign
Binary Search + Deque
binary-search-deque-by-kaicool9789-z8o3
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
kaicool9789
NORMAL
2024-03-15T06:48:54.723879+00:00
2024-03-15T06:48:54.723914+00:00
47
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 maxTaskAssign(vector<int>& t, vector<int>& w, int pills, int strength) {\n int n = t.size();\n int m = w.size();\n sort(t.begin(), t.end());\n sort(w.begin(), w.end());\n auto valid = [&](int val) {\n int npill = pills;\n deque<int> d;\n int sti = 0;\n for (int i = m- val; i < m; i++) {\n while (sti < val && t[sti] <= w[i] + strength) {\n d.push_back(t[sti]);\n sti++;\n }\n if (!d.size()) return false;\n if (d.front() <= w[i]) {\n d.pop_front();\n } else if (npill > 0) {\n npill--;\n d.pop_back();\n } else {\n return false;\n }\n }\n return true;\n };\n int l = 0, r = min(m, n);\n int ans = 0;\n while (l<=r) {\n int mid = (l+r)/2;\n if (valid(mid)) {\n ans = mid;\n l = mid + 1;\n } else {\n r = mid - 1;\n }\n }\n return ans;\n }\n};\n```
0
0
['Binary Search', 'C++']
0
maximum-number-of-tasks-you-can-assign
👏👏👏👏👏Runtime 840 ms Beats 50.00% of users with Go
runtime-840-ms-beats-5000-of-users-with-7516n
Code\n\nfunc maxTaskAssign(tasks []int, workers []int, pills int, strength int) int {\n n := len(tasks)\n\tm := len(workers)\n\n\t// Sorting the tasks and wo
pvt2024
NORMAL
2024-02-24T03:30:11.236327+00:00
2024-02-24T03:30:11.236346+00:00
12
false
# Code\n```\nfunc maxTaskAssign(tasks []int, workers []int, pills int, strength int) int {\n n := len(tasks)\n\tm := len(workers)\n\n\t// Sorting the tasks and workers in increasing order\n\tsort.Ints(tasks)\n\tsort.Ints(workers)\n\tlo := 0\n\thi := min(m, n)\n\tans := -1\n\n\tfor lo <= hi {\n\t\tmid := lo + (hi-lo)/2\n\t\tcount := 0\n\t\tflag := true\n\n\t\t// Copying workers to a new slice\n\t\tst := make([]int, len(workers))\n\t\tcopy(st, workers)\n\n\t\t// Checking if the mid smallest tasks can be assigned\n\t\tfor i := mid - 1; i >= 0; i-- {\n\t\t\t// Case 1: Trying to assign to a worker without the pill\n\t\t\tit := st[len(st)-1]\n\t\t\tif tasks[i] <= it {\n\t\t\t\t// Case 1 satisfied!\n\t\t\t\tst = st[:len(st)-1]\n\t\t\t} else {\n\t\t\t\t// Case 2: Trying to assign to a worker with the pill\n\t\t\t\tit = sort.SearchInts(st, tasks[i]-strength)\n\t\t\t\tif it != len(st) {\n\t\t\t\t\t// Case 2 satisfied!\n\t\t\t\t\tcount++\n\t\t\t\t\tst = append(st[:it], st[it+1:]...)\n\t\t\t\t} else {\n\t\t\t\t\t// Case 3: Impossible to assign mid tasks\n\t\t\t\t\tflag = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If at any moment, the number of pills required for mid tasks exceeds\n\t\t\t// the allotted number of pills, we stop the loop\n\t\t\tif count > pills {\n\t\t\t\tflag = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif flag {\n\t\t\tans = mid\n\t\t\tlo = mid + 1\n\t\t} else {\n\t\t\thi = mid - 1\n\t\t}\n\t}\n\n\treturn ans\n}\n\nfunc min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}\n```
0
0
['Go']
0
maximum-number-of-tasks-you-can-assign
Greedy+Binary search + Deque
greedybinary-search-deque-by-hidanie-xpx1
Intuition\n Describe your first thoughts on how to solve this problem. \nThere are two stages:\nA. A binary scan should be used to check the amount of work that
hidanie
NORMAL
2023-12-28T18:07:40.560013+00:00
2023-12-28T18:07:40.560031+00:00
172
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThere are two stages:\nA. A binary scan should be used to check the amount of work that can be done.\nB. To check if it is possible to do a job of size n, you have to check for each worker if he can do it without a pill and otherwise look for the most difficult job he can do with the pill.\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\nimport java.util.Collection;class Solution {\n \n public int maxTaskAssign(int[] tasks, int[] workers, int pills, int strength) {\n int len = workers.length;\n Arrays.sort(tasks);\n Arrays.sort(workers);\n\n int left = len - Math.min(tasks.length, workers.length);\n int right = len;\n\n while (left < right) {\n int mid = (left + right) / 2;\n boolean canComplete = gg(tasks, workers, pills, strength, mid);\n \n if (canComplete) {\n right = mid;\n } else {\n left = mid + 1;\n }\n }\n\n return len - left;\n }\n\n boolean gg(int[] tasks, int[] workers, int pills, int strength,int begin)\n {\n Deque<Integer>d=new LinkedList<>();\n if(begin==workers.length)\n return false;\n int i=0;\n for(int j=begin;j<workers.length;j++)\n {\n if(!d.isEmpty())\n {\n if(d.peek()<=workers[j])\n d.poll();\n else{\n if(pills==0)\n return false;\n while(i<tasks.length&&tasks[i]<=workers[j]+strength)\n d.add(tasks[i++]);\n d.pollLast();\n pills--;\n }\n }\n else\n if(i==tasks.length)\n return false;\n else if(tasks[i]<=workers[j])\n i++;\n else\n if(pills==0)\n return false;\n else{\n while(i<tasks.length&&tasks[i]<=workers[j]+strength)\n d.add(tasks[i++]);\n if(d.isEmpty())\n return false;\n d.pollLast();\n pills--;\n }\n }\n return true;\n }\n \n \n}\n```
0
0
['Java']
0
maximum-number-of-tasks-you-can-assign
Python 100%
python-100-by-dkoshman-wnpp
Code\n\nimport bisect\nimport collections\n\ndef binsearch(low, high, do_not_search_less_than):\n while high - low > 1:\n mid = (low + high) // 2\n
dkoshman
NORMAL
2023-12-26T11:28:25.042057+00:00
2023-12-26T11:28:25.042097+00:00
26
false
# Code\n```\nimport bisect\nimport collections\n\ndef binsearch(low, high, do_not_search_less_than):\n while high - low > 1:\n mid = (low + high) // 2\n if do_not_search_less_than(mid):\n low = mid\n else:\n high = mid\n return low\n\nclass TaskAssigner:\n def __init__(self, tasks, workers, pills, strength):\n self.tasks = sorted(tasks)\n self.workers = sorted(workers)\n self.pills = pills\n self.strength = strength\n\n def can_assign_k_tasks(self, k):\n tasks = collections.deque(self.tasks[:k])\n pills = self.pills\n for worker in self.workers[-k:]:\n if tasks[0] <= worker:\n tasks.popleft()\n elif not pills or worker + self.strength < tasks[0]:\n return False\n else:\n del tasks[bisect.bisect(tasks, worker + self.strength) - 1]\n pills -= 1\n return True\n\nclass Solution:\n def maxTaskAssign(self, tasks: List[int], workers: List[int], pills: int, strength: int) -> int:\n task_assigner = TaskAssigner(tasks, workers, pills, strength)\n return binsearch(0, min(len(tasks), len(workers)) + 1, task_assigner.can_assign_k_tasks)\n \n```
0
0
['Python3']
0
maximum-number-of-tasks-you-can-assign
MaxTask || Binary Search + Greedy || Java || TreeMap || MultiSet || Predicate Function
maxtask-binary-search-greedy-java-treema-0whe
\nclass Solution {\n public int maxTaskAssign(int[] tasks, int[] workers, int pills, int strength) {\n int ans = 0;\n int low = 0;\n int
jyothi_prakash
NORMAL
2023-12-03T11:41:33.597188+00:00
2023-12-03T11:41:33.597244+00:00
2
false
```\nclass Solution {\n public int maxTaskAssign(int[] tasks, int[] workers, int pills, int strength) {\n int ans = 0;\n int low = 0;\n int high = tasks.length;\n \n Arrays.sort(workers);\n Arrays.sort(tasks);\n \n while(low<=high){\n int mid = low+(high-low)/2;\n boolean possible = isPossible(workers,mid,tasks, pills, strength);\n if(possible){\n ans = mid;\n low = mid+1;\n }\n else{\n high = mid-1;\n }\n }\n \n \n return ans; \n }\n \n public boolean isPossible(int[] workers, int mid, int[] tasks, int pills, int strength){\n // Check can we solve k tasks\n TreeMap<Integer, Integer> map = new TreeMap<>();\n for(int i=0;i<mid;i++){\n int task = tasks[i];\n int occ = map.getOrDefault(task,0);\n map.put(task, occ+1);\n }\n \n \n // System.out.println(map);\n \n for(int i=workers.length-mid;i<workers.length;i++){\n if(i<0){return false;}\n int worker = workers[i];\n // System.out.println(workers[i]);\n Integer exits = map.floorKey(worker);\n if(exits != null){\n int occ = map.get(exits);\n if(occ==1) {map.remove(exits);}\n else {map.put(exits, occ-1);}\n }\n else if(exits == null && pills>0){\n Integer exits2 = map.floorKey(worker+strength);\n if(exits2 == null){return false;}\n int occ = map.get(exits2);\n if(occ==1) {map.remove(exits2);}\n else {map.put(exits2, occ-1);}\n pills-=1;\n }\n else{\n return false;\n }\n // System.out.println(map);\n }\n \n return true;\n \n \n }\n}\n```\n\n\n1. we pick K smallest tasks and assign them to K strongest workers.\n2. Check if they can solve it or not, if not then give one magic pill and again check\n3. If we are able to solve that is one of the potential answer.\n4. else not an answer.\n\n\n\n
0
0
[]
0
maximum-number-of-tasks-you-can-assign
Binary Search + Linear Greedy in Python3
binary-search-linear-greedy-in-python3-b-a0uf
Intuition\n Describe your first thoughts on how to solve this problem. \nThis solution employs binary search to find the largest $k$ so that $k$ tasks can be co
metaphysicalist
NORMAL
2023-11-28T14:18:10.478729+00:00
2023-11-28T14:18:10.478768+00:00
193
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis solution employs binary search to find the largest $k$ so that $k$ tasks can be completed by $k$ workers. To check if $k$ tasks can be completed, this solution performs an efficient linear time greedy algorithm by using a monotonic queue. Thus, the complexity of the whole procedure is only $O(N \\log N)$ without the use of binary search tree or heap. \n\n# Complexity\n- Time complexity: $O(N \\log N)$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $O(N)$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxTaskAssign(self, tasks: List[int], workers: List[int], pills: int, strength: int) -> int:\n tasks.sort()\n workers.sort()\n\n def valid(m):\n wrkrs = deque(workers[-m:])\n pilled = deque()\n not_pilled = deque()\n p = pills\n for t in tasks[:m]:\n while wrkrs and wrkrs[0] < t:\n if p == 0 or wrkrs[0] + strength < t:\n return False\n pilled.append(wrkrs.popleft() + strength)\n p -= 1\n while not_pilled and (p == 0 or not_pilled[0] + strength < t):\n not_pilled.popleft()\n if pilled and ((not wrkrs) or pilled[0] <= wrkrs[0]):\n if pilled[0] >= t:\n pilled.popleft()\n elif not_pilled and p > 0:\n not_pilled.popleft()\n pilled.popleft()\n p -= 1\n else:\n return False\n elif wrkrs:\n not_pilled.append(wrkrs.popleft())\n else:\n return False \n return True\n\n l, r = 1, min(len(tasks), len(workers)) + 1\n while l < r:\n m = (l + r) // 2\n if valid(m):\n l = m + 1\n else:\n r = m\n return l - 1\n```
0
0
['Binary Search', 'Monotonic Queue', 'Python3']
0
maximum-number-of-tasks-you-can-assign
Binary Search + Greedy
binary-search-greedy-by-tanmaygoyal_13-j6xm
Intuition\nTo check how to solve the easiest m tasks using the strongest m workers.\n\n# Approach\nSort the task and worker strenght vectors in increasing order
tanmaygoyal_13
NORMAL
2023-09-08T16:06:06.874252+00:00
2023-09-08T16:06:06.874271+00:00
101
false
# Intuition\nTo check how to solve the easiest m tasks using the strongest m workers.\n\n# Approach\nSort the task and worker strenght vectors in increasing order. Then, binary search over the number of tasks that can be completed using the provided workers and the pills. \n\nFor each of the chosen m easiest tasks, make a multiset of the m strongest workers. For every task in the decreasing order of the m tasks, check if the current strongest worker can complete the task. If so remove the worker and continue. \n\nIf not, chose the weakest possible worker that can complete the given task with the usage of the pills. If the pills are finished or there does not exist any worker that can solve the given task with the pill, that means that the current task would remain undone. Thus, the chosen m tasks would not get completed with the m strongest workers.\n\n# Complexity\n- Time complexity: \n\n\n- Space complexity:\n\n\n# Code\n```\nclass Solution {\npublic:\n int maxTaskAssign(vector<int>& tasks, vector<int>& work, int pills, int strength) {\n int l = 0, r = min(tasks.size(),work.size());\n int ans = l;\n sort(tasks.begin(),tasks.end());\n sort(work.begin(),work.end());\n while(l <= r){\n int m = (l+r)/2, curr = pills;\n multiset<int>mst(end(work)-m,end(work));\n for(int i=m-1;i>=0;i--){\n auto end_ptr = prev(end(mst));\n if(*(end_ptr) < tasks[i]){\n end_ptr = mst.lower_bound(tasks[i] - strength);\n if(end_ptr == mst.end() || curr <= 0){\n break;\n }\n curr--;\n }\n mst.erase(end_ptr);\n }\n if(mst.size() == 0){\n ans = m;\n l = m + 1;\n }\n else r = m - 1;\n }\n return ans;\n }\n};\n```
0
0
['C++']
0
maximum-number-of-tasks-you-can-assign
Sorting and Searching Solution based on given hint
sorting-and-searching-solution-based-on-jwqn2
Code\n\nclass Solution {\npublic:\n int maxTaskAssign(vector<int>& task, vector<int>& workers, int pills, int strength) {\n int t=task.size(),w=worker
Putul77
NORMAL
2023-07-28T15:09:36.862002+00:00
2023-07-28T15:09:51.370273+00:00
111
false
# Code\n```\nclass Solution {\npublic:\n int maxTaskAssign(vector<int>& task, vector<int>& workers, int pills, int strength) {\n int t=task.size(),w=workers.size();\n sort(task.begin(),task.end());\n int ans=0;\n sort(workers.begin(),workers.end());\n int start=0,end=min(t,w)-1;\n\n while(start<=end)\n {\n int mid=start+(end-start)/2;\n if(isPossible(mid,task,workers,pills,strength)){\n ans=max(ans,mid+1);\n start=mid+1;\n }\n else{\n end=mid-1;\n }\n }\n return ans;\n }\n bool isPossible(int ele,vector<int>& task,vector<int>& worker,int pills,int strength)\n {\n multiset<int> ms;\n int t=task.size(),w=worker.size();\n for(int i=0;i<w;i++)\n ms.insert(worker[i]);\n\n for(int i=ele;i>=0;i--)\n {\n auto it=ms.end();\n it--;\n if(*it<task[i])\n {\n if(pills<=0)\n return false;\n \n auto ite=ms.lower_bound(task[i]-strength);\n // Find the iterator to the first element not less than 30\n \n if(ite==ms.end())\n return false;\n pills--;\n ms.erase(ite);\n }\n else{\n ms.erase(it);\n }\n }\n return true;\n }\n};\n```
0
0
['Binary Search', 'Sorting', 'C++']
0
maximum-number-of-tasks-you-can-assign
Python 3 (No binary search) Faster than 100%
python-3-no-binary-search-faster-than-10-p5rp
\n# Intuition\n Describe your first thoughts on how to solve this problem. \nThe inituition: Starts with realizing that you can complete at most k tasks. \nWher
xxx1xxx1
NORMAL
2023-07-27T20:54:45.745472+00:00
2023-07-27T20:54:45.745490+00:00
53
false
![Screenshot 2023-07-27 at 1.28.48 PM.png](https://assets.leetcode.com/users/images/502027f1-967d-4dc5-86f9-5023ae6a8bde_1690491263.5724463.png)\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe inituition: Starts with realizing that you can complete at most k tasks. \nWhere `k = min(len(tasks), len(workers))`\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe split up the workers and task by the k strongest workers and the k weakest tasks. Assign the worker with the minimum required strength the task, remove the worker from the stack.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n- n = len(tasks)\n- m = len(workers)\n- k = min(n, m)\n\n- sorting: $$O(nlogn) + O(mlogm)$$\n- loop: $$O(k*k*logk)$$ - I think the reality is closer to $$O(k*1*logk) = O(klogk)$$\n\nOverall Time Complexity: $$O(nlogn + mlogm + klogk)$$\n- Space complexity: $$O(n + m)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n\n def maxTaskAssign(self, tasks: List[int], workers: List[int], pills: int, strength: int) -> int:\n\n # sort the arrays\n tasks.sort() # O(nlogn)\n workers.sort() # O(mlogm)\n \n \n # you can complete at most k tasks\n k = min(len(tasks), len(workers))\n\n # strongest workers\n workers = workers[-k:]\n\n # easiest tasks\n tasks = tasks[:k]\n\n res = 0\n\n # hardest task first\n for t in reversed(tasks): # O(k)\n # We dont need to use our pills as there\n # exists a worker that can solve the current task\n if workers[-1] >= t:\n res += 1\n # Find the worker with the minimum required strength\n # to complete the ask\n deleteIdx = bisect.bisect_left(workers, t - strength) # O(log k) \n # Remove the worker from the stack\n workers.pop(deleteIdx) # O(k) - my guess is this is closer to O(1) as the worker is going to be closer to the end of the stack\n # we know there exists a worker\n # that can solve the task with a pill\n elif pills and workers[-1] + strength >= t:\n deleteIdx = bisect.bisect_left(workers, t - strength)\n workers.pop(deleteIdx)\n pills -= 1\n res += 1\n # else:\n # The task couldn\'t be solved.\n # Either because we are out of pills\n # or there is no workers that with\n # or without the pill can solve it\n \n return res\n```
0
0
['Stack', 'Monotonic Stack', 'Python3']
1
maximum-number-of-tasks-you-can-assign
Binary Search || Multi Set || C++
binary-search-multi-set-c-by-scrapernerd-j6np
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
ScraperNerd
NORMAL
2023-07-25T18:13:16.688593+00:00
2023-07-25T18:13:16.688611+00:00
37
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool solve(vector<int>& tasks, vector<int>& workers, int pills, int strength, int n){\n multiset<int>mw(workers.end()-n,workers.end());\n for(int i=n-1;i>=0;i--){\n auto it=mw.lower_bound(tasks[i]);\n if(it==mw.end()){\n pills-=1;\n it=mw.lower_bound(tasks[i]-strength);\n }\n if(it==mw.end() or pills<0) return false;\n mw.erase(it);\n }\n return true;\n }\n int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills, int strength) {\n sort(tasks.begin(), tasks.end());\n sort(workers.begin(), workers.end());\n int l=0;\n int h=min(tasks.size(),workers.size());\n int ans=0;\n while(l<=h){\n int mid=(l+h)/2;\n if(solve(tasks,workers,pills,strength,mid)){\n ans=max(mid,ans);\n l=mid+1;\n }\n else h=mid-1;\n }\n return ans;\n }\n};\n\n```
0
0
['C++']
0
maximum-number-of-tasks-you-can-assign
Easy, Simple and Fastest way in C++
easy-simple-and-fastest-way-in-c-by-ashu-zipx
Complexity\n- Time complexity:\nO(wLen*tLen)\n\n- Space complexity:\nO(wLen)\n\n# Code\n\nclass Solution {\n bool checkTask(vector<int>& tasks, vector<int>&
ashujain
NORMAL
2023-07-01T15:55:39.302657+00:00
2023-07-01T15:55:39.302675+00:00
74
false
# Complexity\n- Time complexity:\nO(wLen*tLen)\n\n- Space complexity:\nO(wLen)\n\n# Code\n```\nclass Solution {\n bool checkTask(vector<int>& tasks, vector<int>& workers, int pills, int strength, int mid) {\n multiset<int> mSet(workers.begin(), workers.end());\n\n for(int i = mid-1; i>=0; i--) {\n auto lb = mSet.lower_bound(tasks[i]);\n if(lb != mSet.end()) {\n mSet.erase(lb);\n }\n else {\n if(pills<=0) return false;\n\n auto lb = mSet.lower_bound(tasks[i]-strength);\n if(lb != mSet.end()) {\n mSet.erase(lb);\n pills--;\n }\n else {\n return false;\n }\n }\n }\n\n return true;\n }\npublic:\n int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills, int strength) {\n sort(tasks.begin(), tasks.end());\n sort(workers.begin(), workers.end());\n int t_Len = tasks.size();\n int w_Len = workers.size();\n\n int low=0, high=min(t_Len, w_Len), mid=0;\n int res=0;\n\n while(low <= high) {\n mid = low + (high-low)/2;\n\n if(checkTask(tasks, workers, pills, strength, mid)) {\n low = mid+1;\n res = mid;\n }\n else {\n high = mid-1;\n }\n }\n\n\n return res;\n }\n};\n```
0
0
['C++']
0
maximum-number-of-tasks-you-can-assign
BINARY SEARCH SOLUTION
binary-search-solution-by-parwez0786-4s7d
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
parwez0786
NORMAL
2023-06-21T13:22:33.986602+00:00
2023-06-21T13:22:33.986621+00:00
43
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool isValid(vector<int>& tasks, vector<int>& workers,int ind, int pills, int strength){\n multiset<int>st;\n for(auto it: workers){\n st.insert(it);\n }\n for(int i=ind-1; i>=0; i--){\n auto it=st.lower_bound(tasks[i]);\n if(it!=st.end()){\n st.erase(it);\n }\n else{\n if(pills<=0){\n return false;\n }\n else{\n it=st.lower_bound(tasks[i]-strength);\n if(it!=st.end()){\n st.erase(it);\n pills--;\n }\n else{\n return false;\n }\n\n }\n }\n }\n return true;\n }\n int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills, int strength) {\n //we will use binary search\n // sort task and workers\n // at low=1 high=min(T, W);\n // will find mid \n // will check wthether we can complete mid number of task \n // if yes then set low=mid;\n // else high=mid-1;\n //is valid(mid)\n // in this function we will puts workes in multiset \n // we will iterate from tasks which require large amoiu\n // we will check in multiset task just close to workers strength\n // if we found then increment the count remove it from set\n // if we are not able to find the workers of required strength then we will use pills and try to again find the workers with strength atleast(task-strength if we have available pills)\n int T=tasks.size();\n int W=workers.size();\n sort(tasks.begin(), tasks.end());\n sort(workers.begin(), workers.end());\n int low=0;\n int high=min(T, W);\n while(low<high){\n int mid=(low+high+1)/2;\n \n if(isValid(tasks, workers, mid, pills, strength)){\n low=mid;\n\n }\n else{\n high=mid-1;\n }\n\n }\n\n \n return high;\n\n\n }\n};\n```
0
0
['C++']
0
maximum-number-of-tasks-you-can-assign
Apply Binary Search on Answer!!!✌️🔥🔥🔥
apply-binary-search-on-answer-by-yashpad-sbwr
\n\n# Code\n\nclass Solution {\npublic:\n bool f(int mid,vector<int>& tasks, vector<int>& workers,int pills,int strength){\n multiset<int>ms;\n fo
yashpadiyar4
NORMAL
2023-06-01T13:32:31.946478+00:00
2023-06-01T13:32:31.946547+00:00
118
false
\n\n# Code\n```\nclass Solution {\npublic:\n bool f(int mid,vector<int>& tasks, vector<int>& workers,int pills,int strength){\n multiset<int>ms;\n for(int i=workers.size()-1;i>=0;i--){\n ms.insert(workers[i]);\n }\n for(int i=mid-1;i>=0;i--){\n auto it=ms.end();\n it--;\n if(*it<tasks[i]){\n if(pills<=0)return false;\n auto ite=ms.lower_bound(tasks[i]-strength);\n if(ite==ms.end()){\n return false;\n }\n pills--;\n ms.erase(ite);\n }\n else{\n ms.erase(it);\n }\n }\n return true;\n }\n int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills, int strength) {\n int s=0;\n int e=min(tasks.size(),workers.size());\n int ans=0;\n sort(tasks.begin(),tasks.end());\n sort(workers.begin(),workers.end());\n while(s<=e){\n int mid=s+(e-s)/2;\n if(f(mid,tasks,workers,pills,strength)){\n ans=mid;\n s=mid+1;\n }\n else{\n e=mid-1;\n }\n }\n return ans;\n \n }\n};\n```
0
0
['Binary Search', 'Greedy', 'Sorting', 'C++']
0
maximum-number-of-tasks-you-can-assign
Easy C++ Code
easy-c-code-by-rishabhjain26012002-66e3
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
rishabhjain26012002
NORMAL
2023-05-26T06:13:55.012465+00:00
2023-05-26T06:13:55.012505+00:00
79
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 maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills, int strength) \n {\n sort(tasks.begin(), tasks.end());\n sort(workers.begin(), workers.end());\n int left = 0, right = tasks.size();\n while (left < right)\n {\n int mid = right - (right - left)/2;\n if (checkOK(tasks, workers, pills, strength, mid))\n left = mid;\n else\n right = mid-1;\n }\n return left; \n }\n \n bool checkOK(vector<int>& tasks, vector<int>& workers, int pills, int strength, int num)\n {\n if (num > tasks.size()) return false;\n if (num > workers.size()) return false;\n \n multiset<int>Set(workers.begin(), workers.end()); \n \n for (int i=num-1; i>=0; i--)\n { \n if (*Set.rbegin() >= tasks[i]) \n {\n Set.erase(prev(Set.end()));\n }\n else \n {\n if (pills == 0) return false;\n auto iter = Set.lower_bound(tasks[i]-strength);\n if (iter == Set.end()) return false;\n Set.erase(iter); \n pills--;\n }\n }\n return true;\n }\n};\n```
0
0
['C++']
0
maximum-number-of-tasks-you-can-assign
Python (Simple Binary Search)
python-simple-binary-search-by-rnotappl-0bul
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
rnotappl
NORMAL
2023-04-18T21:43:46.963820+00:00
2023-04-18T21:43:46.963850+00:00
60
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxTaskAssign(self, tasks, workers, pills, strength):\n tasks.sort()\n workers.sort()\n\n def fn(k,pills):\n ww = workers[-k:]\n \n for t in reversed(tasks[:k]):\n if t <= ww[-1]: ww.pop()\n elif pills and t <= ww[-1] + strength:\n pills -= 1\n i = bisect_left(ww,t-strength)\n ww.pop(i)\n else:\n return False\n\n return True\n \n low, high = 0, min(len(tasks),len(workers))\n\n while low <= high:\n mid = (low + high)//2\n if fn(mid,pills): low = mid + 1\n else: high = mid - 1\n\n return high\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n```
0
0
['Python3']
0
maximum-number-of-tasks-you-can-assign
C++
c-by-tinachien-e2ru
\nclass Solution {\n bool check(int k, const vector<int>& tasks, const vector<int>& workers, int pills, int strength){\n int idxW = 0 ;\n int f
TinaChien
NORMAL
2023-04-09T02:05:53.165761+00:00
2023-04-09T02:05:53.165801+00:00
20
false
```\nclass Solution {\n bool check(int k, const vector<int>& tasks, const vector<int>& workers, int pills, int strength){\n int idxW = 0 ;\n int finish = 0 ;\n multiset<int>Set(workers.end() - k, workers.end()) ;\n\n for(int i = k-1; i >= 0; i--){ \n if(*Set.rbegin() >= tasks[i])\n Set.erase(prev(Set.end()) );\n else{\n if(pills == 0)\n return false ;\n auto iter = Set.lower_bound(tasks[i] - strength) ;\n if(iter == Set.end())\n return false ;\n Set.erase(iter) ;\n pills-- ;\n }\n }\n return true ;\n }\npublic:\n int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills, int strength) {\n sort(tasks.begin(), tasks.end()) ;\n sort(workers.begin(), workers.end()) ;\n int left = 0, right = min(tasks.size(), workers.size() ) ;\n while(left < right){\n int mid = right - (right -left)/2 ;\n if(check(mid, tasks, workers, pills, strength))\n left = mid ;\n else\n right = mid - 1 ;\n }\n return left ;\n }\n};\n```
0
0
['Sorting', 'Binary Tree']
0
maximum-number-of-tasks-you-can-assign
Just a runnable solution
just-a-runnable-solution-by-ssrlive-jehc
Code\n\nimpl Solution {\n pub fn max_task_assign(tasks: Vec<i32>, workers: Vec<i32>, pills: i32, strength: i32) -> i32 {\n use std::collections::VecDe
ssrlive
NORMAL
2023-03-08T10:22:45.432423+00:00
2023-03-08T10:22:45.432460+00:00
21
false
# Code\n```\nimpl Solution {\n pub fn max_task_assign(tasks: Vec<i32>, workers: Vec<i32>, pills: i32, strength: i32) -> i32 {\n use std::collections::VecDeque;\n\n fn check(tasks: &[i32], workers: &[i32], pills: i32, strength: i32, k: usize) -> bool {\n let mut pills = pills;\n if k > workers.len() {\n return false;\n }\n let mut t = 0;\n let mut q = VecDeque::new();\n for i in (0..k).rev() {\n if q.is_empty() && t < k {\n q.push_front(tasks[t]);\n t += 1;\n }\n if *q.back().unwrap() <= workers[i] {\n q.pop_back();\n } else {\n if pills == 0 {\n return false;\n }\n if *q.back().unwrap() > workers[i] + strength {\n return false;\n }\n while t < k && tasks[t] <= workers[i] + strength {\n q.push_front(tasks[t]);\n t += 1;\n }\n q.pop_front();\n pills -= 1;\n }\n }\n true\n }\n\n let (mut l, mut r) = (0, tasks.len());\n let mut tasks = tasks;\n let mut workers = workers;\n tasks.sort();\n workers.sort_by(|a, b| b.cmp(a));\n while l < r {\n let mid = (l + r + 1) / 2;\n if check(&tasks, &workers, pills, strength, mid) {\n l = mid;\n } else {\n r = mid - 1;\n }\n }\n l as i32\n }\n}\n```
0
0
['Rust']
0
maximum-number-of-tasks-you-can-assign
binary search and deque
binary-search-and-deque-by-jingnan4-n99w
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
jingnan4
NORMAL
2023-01-31T01:22:52.181515+00:00
2023-01-31T01:25:14.397605+00:00
280
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)$$ -->\nnlogn\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\no(n)\n# Code\n```\nclass Solution {\n public int maxTaskAssign(int[] tasks, int[] workers, int pills, int strength) {\n Arrays.sort(tasks);\n Arrays.sort(workers);\n\n int lo=0,hi=Math.min(tasks.length, workers.length);\n\n while(lo<hi) {\n int mid = (lo+hi+1)/2;\n if(check(mid,tasks,workers,pills,strength)) {\n lo = mid;\n } else {\n hi = mid-1;\n }\n }\n return lo;\n }\n\n boolean check(int k, int[] tasks, int[] workers, int pills, int strength) {\n Deque<Integer> q = new LinkedList<>();\n int j = workers.length-1;\n for(int i=k-1; i>=0; i--) {\n while(j>=workers.length-k && (workers[j]>=tasks[i] || workers[j] + strength>= tasks[i])) {\n q.addFirst(workers[j]);\n j--;\n }\n if(q.isEmpty())\n return false;\n if(q.getLast()>=tasks[i]){\n q.pollLast();\n } else {\n if(pills<=0)\n return false;\n q.pollFirst();\n pills--;\n }\n }\n return true;\n }\n}\n```
0
0
['Java']
0
maximum-number-of-tasks-you-can-assign
[JavaScript/C++] BinarySearch, Queue
javascriptc-binarysearch-queue-by-tmohan-gndn
Greedy Approach\n- Pills are precious, so avoid using them as much as possible\n- In case we are forced to use pills, give pill to lower potential worker who ca
tmohan
NORMAL
2023-01-10T06:24:35.230894+00:00
2023-01-10T06:38:05.878089+00:00
176
false
# Greedy Approach\n- Pills are precious, so avoid using them as much as possible\n- In case we are forced to use pills, give pill to lower potential worker who can complete the task, i.e., **workerEngergy < task --whereas-- workerEnergy + strengthFromOnePill >= task**\n- deque store the workers in decreasing order of their potential\n\n# Complexity\n- Time complexity: $$O(n^2)$$\n- Space complexity: $$O(n)$$\n# Code\n```\nclass Solution {\npublic:\n int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills, int strength) {\n sort(begin(workers), end(workers));\n sort(begin(tasks), end(tasks));\n\n int lTasks = -1, rTasks = min(tasks.size(), workers.size()) - 1;\n\n while (lTasks < rTasks) {\n int midTasks = (lTasks + rTasks + 1) >> 1, t = midTasks;\n deque<int> dq;\n\n for (int w = workers.size() - 1, freePills = pills; t >= 0; t--) {\n if (dq.size() > 0 && dq.front() >= tasks.at(t)) {\n dq.pop_front();\n } else if (w >= 0 && workers.at(w) >= tasks.at(t)) {\n w--;\n } else if (freePills > 0) {\n while (w >= 0 && workers.at(w) + strength >= tasks.at(t))\n dq.push_back(workers.at(w--));\n\n if (dq.size() == 0) break;\n dq.pop_back(), freePills--;\n } else break;\n }\n\n t == -1 ? lTasks = midTasks : rTasks = midTasks - 1;\n }\n\n return lTasks + 1;\n }\n};\n```\n```\nvar maxTaskAssign = function(tasks, workers, pills, strength) {\n workers.sort((b, a) => b - a);\n tasks.sort((b, a) => b - a);\n\n let lTasks = -1, rTasks = Math.min(tasks.length, workers.length) - 1;\n\n while (lTasks < rTasks) {\n const midTasks = (lTasks + rTasks + 1) >> 1;\n let t = midTasks;\n\n for (let w = workers.length - 1, freePills = pills, queue = []; t >= 0; t--) {\n if (queue[0] >= tasks[t]) {\n queue.shift();\n } else if (workers[w] >= tasks[t]) {\n w--;\n } else if (freePills > 0) {\n while (w >= 0 && workers[w] + strength >= tasks[t])\n queue.push(workers[w--]);\n\n if (queue.length == 0) break;\n queue.pop(), freePills--;\n } else break;\n }\n t == -1 ? lTasks = midTasks : rTasks = midTasks - 1;\n }\n return lTasks + 1;\n};\n```
0
0
['Binary Search', 'Queue', 'Sorting', 'C++', 'JavaScript']
0
maximum-number-of-tasks-you-can-assign
Python SortedList OR bisect
python-sortedlist-or-bisect-by-panoslin-knil
There are 2 ways of doing binary search for this problem using Python\nLet N, M be the legth of tasks and worker respectively.\n1. SortedList - TC: logN * N * l
panoslin
NORMAL
2022-12-01T08:18:42.768050+00:00
2022-12-01T08:52:01.481664+00:00
75
false
There are 2 ways of doing binary search for this problem using Python\nLet N, M be the legth of tasks and worker respectively.\n1. SortedList - TC: `logN * N * logM * logM`\n2. bisect &nbsp; &nbsp; &nbsp; &nbsp;- TC: `logN * N * logM * M`\n\nHere\n` logN` is from the outest binary search\n`N` is from the for loop in check() function for `bottom_task`\n`logM` is from `top_workers.bisect_left()`\n\nThe difference between the 2 method is on the `top_workers.pop`.\n`pop` from a SortedList should be taking `logM`\n`pop` from a List in Python with argument should be taking a worst `M`\n\n\nBut when using SortedList it gives TLE. I\'m confused, shouldn\'t SortedList be faster then List in Python when doing a `.pop()` operation?\n\nSortedList solution\n```python\nfrom sortedcontainers import SortedList\n\n\nclass Solution:\n def maxTaskAssign(self, tasks: List[int], workers: List[int], pills: int, strength: int) -> int:\n n, m = len(tasks), len(workers)\n tasks.sort()\n workers.sort()\n \n \n def check(k):\n top_workers = SortedList(workers[-k:])\n bottom_tasks = tasks[:k][::-1]\n pill_needed = 0\n\n for task in bottom_tasks:\n idx = top_workers.bisect_left(task)\n if idx < len(top_workers):\n top_workers.pop(idx)\n continue\n \n idx = top_workers.bisect_left(task - strength)\n if idx < len(top_workers):\n top_workers.pop(idx)\n pill_needed += 1\n else:\n return float(\'inf\')\n\n return pill_needed\n \n left, right = 0, min(n, m)\n while left <= right:\n should_complete = (left + right) // 2\n pill_needed = check(should_complete)\n # print(left, right, should_complete, pill_needed)\n \n if pill_needed <= pills:\n left = should_complete + 1\n else:\n right = should_complete - 1\n \n return right\n```\n\n\nbisect solution:\n```python\nimport bisect\n\n\nclass Solution:\n def maxTaskAssign(self, tasks: List[int], workers: List[int], pills: int, strength: int) -> int:\n n, m = len(tasks), len(workers)\n tasks.sort()\n workers.sort()\n \n\n def check(k):\n top_workers = workers[-k:]\n bottom_tasks = tasks[:k][::-1]\n pill_needed = 0\n\n for task in bottom_tasks:\n idx = bisect.bisect_left(top_workers, task)\n if idx < len(top_workers):\n top_workers.pop(idx)\n continue\n \n idx = bisect.bisect_left(top_workers, task - strength)\n if idx < len(top_workers):\n top_workers.pop(idx)\n pill_needed += 1\n else:\n return float(\'inf\')\n \n return pill_needed\n\n left, right = 0, min(n, m)\n while left <= right:\n should_complete = (left + right) // 2\n pill_needed = check(should_complete)\n # print(left, right, should_complete, pill_needed)\n\n if pill_needed <= pills:\n left = should_complete + 1\n else:\n right = should_complete - 1\n \n return right\n```
0
0
['Binary Tree']
0
maximum-number-of-tasks-you-can-assign
[Python] Binary search and greedy check
python-binary-search-and-greedy-check-by-1phg
\nfrom bisect import bisect_left\n\nclass Solution:\n def maxTaskAssign(self, tasks: List[int], workers: List[int], pills: int, strength: int) -> int:\n
cava
NORMAL
2022-10-13T02:22:06.395856+00:00
2022-10-13T02:22:06.395916+00:00
67
false
```\nfrom bisect import bisect_left\n\nclass Solution:\n def maxTaskAssign(self, tasks: List[int], workers: List[int], pills: int, strength: int) -> int:\n tasks.sort()\n workers.sort()\n ans, lo, hi = 0, 1, min(len(workers), len(tasks))\n while lo <= hi:\n mid = (lo + hi) // 2\n cp, cw = pills, workers[-mid:]\n for i, t in enumerate(reversed(tasks[:mid])):\n if cw[-1] >= t: cw.pop(-1)\n elif cw[-1] + strength >= t and cp:\n pos = bisect_left(cw, t - strength)\n cw[pos : pos + 1] = []\n cp -= 1\n if len(cw) + i + 1 != mid: break\n if cw: hi = mid - 1\n else:\n ans = max(ans, mid)\n lo = mid + 1\n return ans\n```
0
0
[]
0
maximum-number-of-tasks-you-can-assign
Exlplanation why BinearySearch works & Greedy does NOT
exlplanation-why-binearysearch-works-gre-bgp2
\n def maxTaskAssign(self, tasks: List[int], workers: List[int], pills: int, strength: int) -> int:\n \n maxTasks = min(len(tasks), len(workers
sarthakBhandari
NORMAL
2022-09-15T20:38:23.835873+00:00
2022-09-15T20:39:58.584084+00:00
148
false
```\n def maxTaskAssign(self, tasks: List[int], workers: List[int], pills: int, strength: int) -> int:\n \n maxTasks = min(len(tasks), len(workers))\n workers.sort()\n tasks.sort()\n #u can try a greedy approach, I spent days and it got better but it didnt work 100% time\n #but binarySearch approach guarantees the correct solution\n #because u can develop a checking algorithm to check if answer is correct\n \n def isValid(maxTask):\n #find all the workers who can do the c_strongestTask with/without the pill, put them in a que\n #if the first item in que doesnt require pill, use it, otherwise\n #use the last item in que to do the c_task -> this frees up stronger guys to do weaker tasks without pill\n #the next_strongestTask can be handelled by all items in the que, but add some new ones aswell\n #repeat the same process\n #this whole process can be done in Time->O(N), Space->O(N)\n \n #u can also use binarySearch here,Time->O(NlogN), &, \n #pretty sure Space->O(N) because u have to find some way to keep track of workers on which pill was used\n canHandle = deque([])\n t_i = maxTask-1; w_i = len(workers)-1\n pill = pills\n while t_i >= 0:\n c_task = tasks[t_i]\n \n while w_i >= 0 and workers[w_i] + strength >= c_task:\n canHandle.append(workers[w_i])\n w_i -= 1\n if not canHandle: #no worker available to do this task\n return False\n \n if canHandle[0] >= c_task: #strongest available worker can do this task withoutpill\n canHandle.popleft()\n #need to use a pill\n elif pill:\n canHandle.pop()\n pill -= 1\n #no pills left :(\n else:\n return False\n t_i -= 1\n return True\n \n L = 0; R = maxTasks\n while L < R:\n M = (L+R+1)//2\n if isValid(M):\n L = M\n else:\n R = M-1\n \n return L\n```
0
0
['Greedy', 'Binary Tree', 'Python']
0
maximum-number-of-tasks-you-can-assign
[C++] || with komments
c-with-komments-by-gurbeege-39u6
\nint maxTaskAssign(vector<int>& tasks, vector<int>& ws, int pills, int strength) {\n sort(tasks.begin(), tasks.end());\n sort(ws.begin(), ws.end(
Gurbeege
NORMAL
2022-09-12T21:31:19.460111+00:00
2022-09-12T21:31:19.460156+00:00
82
false
```\nint maxTaskAssign(vector<int>& tasks, vector<int>& ws, int pills, int strength) {\n sort(tasks.begin(), tasks.end());\n sort(ws.begin(), ws.end());\n \n \n int l = 0, r = min(tasks.size(), ws.size());\n while(l<r){\n int m = (l+r+1)/2, need = 0;\n \n // using multiset bcz it\'s optimal for removing elements\n // creating set of the strongest \'m\' workers in multiset\n multiset<int> ms(ws.end() - m, end(ws)); \n \n for(int i=m-1; i>=0; --i){\n // iterating over \'m\' smallests tasks\n \n auto it = ms.end();\n it--; // itr of last element of multiset; \n \n if(*it >= tasks[i]){\n // without pill, worker strong enough to do task\n ms.erase(it);\n }\n else{\n // checking if possible with using magic-pill\n it = ms.lower_bound(tasks[i]-strength);\n if(it == end(ms) || ++need > pills)\n break;\n ms.erase(it);\n }\n \n }\n\n if(ms.empty())\n // All \'m\' tasks got a worker assigned to them\n l = m;\n else\n r = m-1;\n }\n return l; \n }\n```
0
0
[]
0
maximum-number-of-tasks-you-can-assign
Greedy + Binary Search
greedy-binary-search-by-aknov711-wddn
\nclass Solution {\npublic:\n int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills, int strength) {\n // is it optimal to give all pi
aknov711
NORMAL
2022-08-23T14:22:10.721159+00:00
2022-08-23T14:22:10.721200+00:00
114
false
```\nclass Solution {\npublic:\n int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills, int strength) {\n // is it optimal to give all pills to the \n // people with highest stength ??? \n \n // No \n \n // Observation : If I give a pill to ith person, then \n // it must be taking some task, otherwise I won\'t \n // be giving him any pill \n \n \n // what if there are no pills ?\n \n // If I can complete any x tasks, I can also complete \n // x smallest tasks \n \n // x1 < x2 < x3 < x4 < ............\n // So, it can\'t be that I assign xi but not xj with j<i \n // So, always start assigning task from 1 \n \n // Binary search on the answer \n int n = tasks.size();\n int m =workers.size();\n \n sort(tasks.begin(),tasks.end());\n \n int low=0;\n int high=n;\n int ans=0;\n while(low<=high){\n int mid=(low+high)/2;\n bool f=true;\n multiset<int>ms;\n \n for(auto e:workers)\n ms.insert(e);\n \n int count=0;\n \n for(int i=mid-1;i>=0;i--){\n auto it=ms.lower_bound(tasks[i]);\n if(it!=ms.end()){\n ms.erase(it);\n continue;\n }\n \n // val + strength >= tasks[i]\n // val>=tasks[i]-strength \n it=ms.lower_bound(tasks[i]-strength);\n \n if(it==ms.end())\n {\n f=false;\n break;\n }\n \n ++count;\n if(count>pills){\n f=false;\n break;\n }\n\n ms.erase(it);\n }\n if(f){\n ans=mid;\n low=mid+1;\n }\n else \n high=mid-1;\n }\n return ans;\n \n \n }\n};\n```
0
0
[]
0
maximum-number-of-tasks-you-can-assign
[C++] Multiset Greedy Binary Search
c-multiset-greedy-binary-search-by-caoba-v6mh
My idea is simple. We have 3 observations:\n1. If we can do n tasks then we can do n-1 tasks => We use binary search to find result.\n2. If we do n tasks we wil
caobaohoang03
NORMAL
2022-08-12T11:26:32.623728+00:00
2022-08-12T11:27:57.437498+00:00
123
false
My idea is simple. We have 3 observations:\n1. If we can do n tasks then we can do n-1 tasks => We use binary search to find result.\n2. If we do n tasks we will chooses n smallest tasks and n highest workers (greedy)\n3. For one worker we will assign it to nearest task. If no nearest task smaller than worker, we will use pill on this worker and find nearest task with new strength => We use binary search to find nearest task.\n\nHere is my code implement this idea. If you find this helpful, please upvote.\n```\nclass Solution {\npublic:\n int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills, int strength) {\n sort(tasks.begin(), tasks.end());\n sort(workers.begin(), workers.end());\n int low = 1;\n int high = min(tasks.size(), workers.size());\n while(low<=high){\n int mid = (low+high)/2;\n int can = 1;\n int temp = pills;\n multiset<int> solved_tasks;\n for(int i = 0; i<mid; i++){\n solved_tasks.insert(tasks[i]);\n }\n \n for(int i=workers.size()-mid; i<workers.size(); i++){\n auto it = solved_tasks.upper_bound(workers[i]);\n if(it != solved_tasks.begin()){\n it--;\n solved_tasks.erase(it);\n continue;\n }\n if(temp==0){\n can = 0;\n break;\n }\n it = solved_tasks.upper_bound(workers[i]+strength);\n if(it != solved_tasks.begin()){\n temp--;\n it --;\n solved_tasks.erase(it);\n }\n else{\n can = 0;\n break;\n }\n }\n if(can){\n low = mid+1;\n }\n else{\n high = mid-1;\n }\n }\n return low-1;\n }\n};
0
0
['Greedy', 'Binary Tree']
0
maximum-number-of-tasks-you-can-assign
python3 O(nlogn) bs+queue
python3-onlogn-bsqueue-by-wenzhenl-mt0n
Note the check takes O(n), starting from the hardest task, if the strongest worker can take it, then let the worker do it, otherwise find the weakest worker who
wenzhenl
NORMAL
2022-08-06T00:25:45.373408+00:00
2022-08-06T00:25:45.373449+00:00
88
false
Note the `check` takes O(n), starting from the hardest task, if the strongest worker can take it, then let the worker do it, otherwise find the weakest worker who can do it with the pill. So we can maintain a queue which contains all workers who can do it with the pill. If the strongest one (`queue[0]`) can do it without pill, good. Otherwise the `queue[-1]` is the weakest one who can do it with pill. For the next task, all remaining in the queue can still do it with the pill, since all of them can do the harder one earlier. So we just need to extend the queue to add these who can do the easier task with the pill now, but was able to do the harder one in last round. At the end, each worker can enter the queue at most once. so total time complexity is O(N)\n\t\n```\nclass Solution:\n def maxTaskAssign(self, tasks: List[int], workers: List[int], pills: int, strength: int) -> int:\n def check(x, tasks, workers, pills, strength):\n queue = collections.deque()\n start = 0\n for i in range(x-1, -1, -1):\n task = tasks[i]\n while start <= min(x-1, len(workers)-1) and workers[start] + strength >= task:\n queue.append(start)\n start += 1\n if not queue:\n return False\n if workers[queue[0]] >= task:\n queue.popleft()\n else:\n pills -= 1\n if pills < 0:\n return False\n queue.pop()\n return True\n \n \n \n tasks = sorted(tasks)\n workers = sorted(workers, reverse=True)\n low, high = 0, len(tasks)\n ans = 0\n while low <= high:\n mid = low + (high - low) // 2\n if check(mid, tasks, workers, pills, strength):\n ans = max(ans, mid)\n low = mid + 1\n else:\n high = mid - 1\n return ans\n```
0
0
[]
0
maximum-number-of-tasks-you-can-assign
Optimal Solution, no Binary Seach O(nlogn)
optimal-solution-no-binary-seach-onlogn-2f1ff
Sort both tasks and workers in decreasing order.\\nLet used denotes a set of workers using pills.\n If the hardest task is smaller than the strongest worker, ad
horizon1006
NORMAL
2022-07-28T19:15:35.383375+00:00
2022-07-28T20:03:15.424774+00:00
129
false
Sort both tasks and workers in decreasing order.\\\nLet `used` denotes a set of workers using pills.\n* If the hardest task is smaller than the strongest worker, add `1` to the answer, remove both of the task and the worker \n* Otherwise, a worker must takes the pills to be able to do the task. As one must be chosen, we would choose the weakest worker than can do the task after taking the pill since there\'s higher chance more tasks can be completed thanks to the stronger strength of other\'s \n* If we could not find a worker can do the task even after taking the pill, or simply there\'s just no pill left, we would force the strongest worker who had taken the pill to quit his taskes and give up his pill and do the task .There are two case. If the worker is stronger than the task, this case we would gain back 1 pill, otherwise the worker would still have to use the pill to complete the task (he took the pill and do a harder task previously so it\'s guaranteed he could do the task if he took one). Either case, the number of completed tasks is unchanged and more pills could possibly be gained, hence we achieve the optimal solution. If there is not such a worker, then simply this task could not done, leave it and proceed to the next one.\n\n```python\ndef maxTaskAssign(self, tasks: List[int], workers: List[int], pills: int, strength: int) -> int:\n tasks.sort(reverse=True)\n from sortedcontainers import SortedList\n pool = SortedList(workers)\n i = res = c = 0\n used = SortedList()\n while i < len(tasks) and pool:\n if tasks[i] <= pool[-1]:\n c += 1\n pool.pop()\n else:\n j = pool.bisect_left(tasks[i] - strength)\n if (j == len(pool) or len(used) == pills) and used:\n pool.add(used.pop())\n continue\n if j < len(pool) and pills:\n used.add(pool.pop(j))\n i += 1\n res = max(res, c + len(used))\n return res\n```
0
0
[]
0
maximum-number-of-tasks-you-can-assign
How can this be wrong ???
how-can-this-be-wrong-by-kumarambuj-hisx
\nclass Solution:\n def maxTaskAssign(self, t: List[int], workers: List[int], pills: int, s: int) -> int:\n \n t.sort()\n workers.sort()
kumarambuj
NORMAL
2022-06-16T06:42:49.686881+00:00
2022-06-16T06:42:49.686932+00:00
157
false
```\nclass Solution:\n def maxTaskAssign(self, t: List[int], workers: List[int], pills: int, s: int) -> int:\n \n t.sort()\n workers.sort()\n \n A=t.copy()\n B=workers.copy()\n p=pills\n ans=0\n a=False\n b=False\n while(len(A)>0 and len(B)>0):\n #print(A,B,p)\n if B[-1]>=A[-1]:\n a=True\n ans+=1\n B.pop()\n A.pop()\n else:\n if p>0 and math.ceil((A[0]-B[0])/s) <=p:\n b=True\n ans+=1\n p=p-math.ceil((A[0]-B[0])/s)\n B.pop()\n A.pop()\n else:\n A.pop()\n \n \n ans1=0\n A=t.copy()\n B=workers.copy()\n a=False\n b=False\n while(len(A)>0 and len(B)>0):\n print(A,B)\n if B[0]>=A[0]:\n a=True\n ans1+=1\n B.pop(0)\n A.pop(0)\n else:\n if pills>0 and math.ceil((A[0]-B[0])/s) <=pills:\n b=True\n ans1+=1\n pills=pills-math.ceil((A[0]-B[0])/s)\n B.pop(0)\n A.pop(0)\n else:\n A.pop(0)\n \n print(ans,ans1)\n return max(ans,ans1)\n \n```\n\nfor the test case\ntasks = [10,15,30], workers = [0,10,10,10,10], pills = 3, strength = 10\ngetting max 3 \nwhich is true\n\nplease someone help
0
0
['Greedy', 'Python']
1
maximum-number-of-tasks-you-can-assign
Java | Binary Search and Greedy | LinkedHashset
java-binary-search-and-greedy-linkedhash-qvte
\n/*\nThe binary search approach is not very obvious here.\n\nThe idea is to pick k easiest tasks, and k strongest workers, and see if we can assign those tasks
wilson_chuks
NORMAL
2022-04-09T06:53:19.563094+00:00
2022-04-09T06:53:19.563142+00:00
306
false
```\n/*\nThe binary search approach is not very obvious here.\n\nThe idea is to pick k easiest tasks, and k strongest workers, and see if we can assign those tasks.\n\nWith this set of k strongest workers and k easiest tasks, we:\n\nProcess tasks from hardest to easiest\nCheck if the strongest worker can do the hardest of the remaining tasks.\nIf not, find the weakest worker that can do the hardest task if given a pill.\nIf there are no more pills, we cannot assign m tasks.\nIf we find the worker who can do the task, remove it from the list of workers.\nIf not, we cannot assign m tasks.\n\nFinally, we do a binary search for the maximum number of tasks that we can accomplish (i.e the max k).\n\nI used linked hashset for searching and removing workers during each process of the binary\nsearch\n*/\nclass Solution {\n //can k strongest workers do k easiest tasks? Use the algorithm above\n \n public int maxTaskAssign(int[] tasks, int[] workers, int pills, int strength) {\n Arrays.sort(tasks);\n Arrays.sort(workers);\n int n = tasks.length, m = workers.length;\n int left = 0, right = Math.min(n,m);\n int index = 0;\n while(left < right){\n int mid = left + (right - left)/2;\n boolean finished = canFinish(index++,tasks, workers, pills, strength, mid+1);\n if(finished){\n left = mid + 1;\n }else {\n right = mid;\n }\n }\n return left;\n }\n //can k strongest workers do k easiest tasks? Use the algorithm above\n public boolean canFinish(int index, int[] tasks, int[] workers, int pills, int strength, int k){\n //take easiest k jobs and strongest k men\n int lastTask = k-1, firstWorker = workers.length-k;\n int lastWorker = workers.length-1;\n int count = 0;\n \n LinkedHashSet<Integer> set = new LinkedHashSet<>();\n for(int i=firstWorker; i<= lastWorker; i++)\n set.add(i);\n \n top:\n while(lastWorker >= firstWorker && lastTask >= 0){\n //check if the worker has been used before without being removed\n if(!set.contains(lastWorker)){\n lastWorker--;\n continue;\n }\n //check if current strongest worker can do the current hardest job\n //without pills\n if(workers[lastWorker] >= tasks[lastTask]){\n set.remove(lastWorker);\n lastWorker--;\n lastTask--;\n count++;\n continue;\n }\n //find the weakest worker that can do current hardest job with pill\n //ensure there is pills left and the worker has not been used before\n boolean workerSeen = false;\n Iterator<Integer> setIt = set.iterator();\n while(setIt.hasNext() && pills > 0){\n int nextWorker = setIt.next();\n \n if(workers[nextWorker] + strength >= tasks[lastTask]){\n pills--;\n lastTask--;\n setIt.remove();\n count++;\n workerSeen = true;\n break;\n }\n }\n if(!workerSeen) return false;\n \n }\n return count == k;\n }\n}\n```
0
0
[]
0
maximum-number-of-tasks-you-can-assign
C++ 96% (Time and Mem) Iterative approach with Priority Queue, commented
c-96-time-and-mem-iterative-approach-wit-5jpv
int maxTaskAssign(vector& tasks, vector& workers, int pills, int strength) {\n \n // Sort in descending order, could sort in ascending. Would just
Tkyl
NORMAL
2022-03-14T18:59:16.078764+00:00
2022-03-14T18:59:16.078794+00:00
499
false
int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills, int strength) {\n \n // Sort in descending order, could sort in ascending. Would just need to change loop iteration direction\n sort(tasks.begin(),tasks.end(),[](int lhs, int rhs) {return lhs > rhs;});\n sort(workers.begin(),workers.end(),[](int lhs, int rhs) {return lhs > rhs;});\n \n int t = 0; // Current task we are assessing\n int w = 0; // Current worker we are checking\n int wp = 0; // Weakest worker than can complete task with a pill\n \n int completedTasks = 0; // Final output\n bool bSearchDown = true; // When false, we\'ve hit the point that all workers can complete remaining tasks with a pill?\n \n priority_queue<int> workersQ; // Workers than have a task assigned to them, but can only complete with a pill. Needs to be in descending order\n \n while(t < tasks.size())\n {\n while(w < workers.size() && workers[w] == -1) w++; // Find next worker that has not already been processed\n \n if(w >= workers.size()) // If we\'ve run out of workers, look to see if any in the queue can solve the task.\n {\n if(!workersQ.empty() && workersQ.top() > tasks[t])\n {\n workersQ.pop();\n completedTasks++;\n }\n }\n else if(workers[w] >= tasks[t]) // If the current worker can solve the task without a pill, use her.\n {\n workers[w] = -1;\n w++;\n completedTasks++;\n }\n else\n {\n if(bSearchDown) // Find the lowest strength worker that can solve the task with a pill\n {\n //Find first worker that can\'t do task with pill\n while(wp < workers.size() && (workers[wp] == -1 || workers[wp] + strength >= tasks[t]))\n {\n wp++;\n }\n \n // All tasks can now be completed by all workers with pill\n if(wp == workers.size())\n {\n bSearchDown = false;\n wp = workers.size() - 1;\n }\n }\n \n // Iterate up till we find a worker that has not been processed and can complete the task. Should be the next valid worker.\n while(wp >= workers.size() || wp > w && (workers[wp] == -1 || workers[wp] + strength < tasks[t]))\n {\n wp--;\n }\n \n // If we have equal or more workers assigned to the queue than pills, see if we can pull one out to finish this task\n if(workersQ.size() >= pills && !workersQ.empty() && workersQ.top() >= tasks[t])\n {\n completedTasks++;\n workersQ.pop();\n }\n // Can wp worker finish the task?\n else if(workers[wp] + strength >= tasks[t])\n {\n workersQ.push(workers[wp]); \n workers[wp] = -1;\n wp += bSearchDown ? -1 : 1;\n }\n // Even if we haven\'t filled queue, check to see if a worker can finish a task without a pill (task would be wasted otherwise)\n else if(!workersQ.empty() && workersQ.top() >= tasks[t])\n {\n completedTasks++;\n workersQ.pop();\n }\n }\n \n t++; // Processed one task\n wp = max(wp,w); // If ever WP becomes greater than w, clamp it to w\n }\n \n return completedTasks + min((int)workersQ.size(), pills); // Return number of completed tasks + number of workers in queue (i.e. number of workers than can complete a task with a pill.)\n }
0
0
['C', 'Heap (Priority Queue)']
0
maximum-number-of-tasks-you-can-assign
Python | greedy + binary search using monotonic que | O(nlogn)
python-greedy-binary-search-using-monoto-jt3r
\nfrom collections import deque\nclass Solution:\n def maxTaskAssign(self, tasks: List[int], workers: List[int], pills: int, strength: int) -> int:\n
aryonbe
NORMAL
2022-02-26T11:30:33.737236+00:00
2022-04-23T13:24:23.045980+00:00
272
false
```\nfrom collections import deque\nclass Solution:\n def maxTaskAssign(self, tasks: List[int], workers: List[int], pills: int, strength: int) -> int:\n tasks = sorted(tasks)\n workers = sorted(workers)\n n = len(workers)\n def check(k, pills):\n que = deque()\n idx = n-1\n for i in range(k-1,-1,-1):\n while idx >= n-k and workers[idx]+strength>=tasks[i]:\n que.append(workers[idx])\n idx -= 1\n if not que:\n return False\n if que[0]>=tasks[i]:\n que.popleft()\n else:\n que.pop()\n pills -= 1\n if pills < 0:\n return False\n return True\n left, right = 0, min(len(tasks),len(workers))+1\n while left+1 < right:\n mid = (left + right)//2\n if check(mid, pills):\n left = mid\n else:\n right = mid\n return left\n```
0
0
[]
0