inputs
stringlengths 50
14k
| targets
stringlengths 4
655k
|
|---|---|
We have jobs: difficulty[i] is the difficulty of the ith job, and profit[i] is the profit of the ith job.
Now we have some workers. worker[i] is the ability of the ith worker, which means that this worker can only complete a job with difficulty at most worker[i].
Every worker can be assigned at most one job, but one job can be completed multiple times.
For example, if 3 people attempt the same job that pays $1, then the total profit will be $3. If a worker cannot complete any job, his profit is $0.
What is the most profit we can make?
Example 1:
Input: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]
Output: 100
Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get profit of [20,20,30,30] seperately.
Notes:
1 <= difficulty.length = profit.length <= 10000
1 <= worker.length <= 10000
difficulty[i], profit[i], worker[i] are in range [1, 10^5]
|
class Solution:
def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:
jobs = list(zip(difficulty, profit))
jobs.sort()
ans = 0
i = 0
best = 0
for skill in sorted(worker):
while i<len(jobs) and skill >= jobs[i][0]:
best = max(best, jobs[i][1])
i += 1
ans += best
return ans
|
We have jobs: difficulty[i] is the difficulty of the ith job, and profit[i] is the profit of the ith job.
Now we have some workers. worker[i] is the ability of the ith worker, which means that this worker can only complete a job with difficulty at most worker[i].
Every worker can be assigned at most one job, but one job can be completed multiple times.
For example, if 3 people attempt the same job that pays $1, then the total profit will be $3. If a worker cannot complete any job, his profit is $0.
What is the most profit we can make?
Example 1:
Input: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]
Output: 100
Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get profit of [20,20,30,30] seperately.
Notes:
1 <= difficulty.length = profit.length <= 10000
1 <= worker.length <= 10000
difficulty[i], profit[i], worker[i] are in range [1, 10^5]
|
class Solution:
def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:
n=max(worker)
s=[0 for i in range(n)]
for i in range(len(difficulty)):
if difficulty[i]<=n :
s[difficulty[i]-1]=max(s[difficulty[i]-1],profit[i])
for i in range(1,n):
if s[i]<s[i-1]:
s[i]=s[i-1]
ans=sum([s[worker[i]-1] for i in range(len(worker))])
return ans
|
We have jobs: difficulty[i] is the difficulty of the ith job, and profit[i] is the profit of the ith job.
Now we have some workers. worker[i] is the ability of the ith worker, which means that this worker can only complete a job with difficulty at most worker[i].
Every worker can be assigned at most one job, but one job can be completed multiple times.
For example, if 3 people attempt the same job that pays $1, then the total profit will be $3. If a worker cannot complete any job, his profit is $0.
What is the most profit we can make?
Example 1:
Input: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]
Output: 100
Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get profit of [20,20,30,30] seperately.
Notes:
1 <= difficulty.length = profit.length <= 10000
1 <= worker.length <= 10000
difficulty[i], profit[i], worker[i] are in range [1, 10^5]
|
class Solution:
def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:
def bs(arr, s, e, target):
while s<=e:
mid = s+(e-s)//2
if arr[mid][0]<=target:
s = mid+1
else:
e = mid-1
return e
arr = []
for pd in sorted(zip(difficulty, profit)):
if arr and arr[-1][1]>=pd[1]:
continue
arr.append(pd)
res = 0
N = len(arr)
for w in worker:
idx = bs(arr, 0, N-1, w)
if idx>=0:
res += arr[idx][1]
return res
|
We have jobs: difficulty[i] is the difficulty of the ith job, and profit[i] is the profit of the ith job.
Now we have some workers. worker[i] is the ability of the ith worker, which means that this worker can only complete a job with difficulty at most worker[i].
Every worker can be assigned at most one job, but one job can be completed multiple times.
For example, if 3 people attempt the same job that pays $1, then the total profit will be $3. If a worker cannot complete any job, his profit is $0.
What is the most profit we can make?
Example 1:
Input: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]
Output: 100
Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get profit of [20,20,30,30] seperately.
Notes:
1 <= difficulty.length = profit.length <= 10000
1 <= worker.length <= 10000
difficulty[i], profit[i], worker[i] are in range [1, 10^5]
|
class Solution:
def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:
n=len(profit)
maxm=max(difficulty)
dp=[0]*(1+maxm)
for i in range(n):
dp[difficulty[i]]=max(dp[difficulty[i]],profit[i])
for i in range(1,maxm+1):
dp[i]=max(dp[i],dp[i-1])
res=0
for x in worker:
if x>maxm:
res+=dp[maxm]
else:
res+=dp[x]
return res
|
We have jobs: difficulty[i] is the difficulty of the ith job, and profit[i] is the profit of the ith job.
Now we have some workers. worker[i] is the ability of the ith worker, which means that this worker can only complete a job with difficulty at most worker[i].
Every worker can be assigned at most one job, but one job can be completed multiple times.
For example, if 3 people attempt the same job that pays $1, then the total profit will be $3. If a worker cannot complete any job, his profit is $0.
What is the most profit we can make?
Example 1:
Input: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]
Output: 100
Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get profit of [20,20,30,30] seperately.
Notes:
1 <= difficulty.length = profit.length <= 10000
1 <= worker.length <= 10000
difficulty[i], profit[i], worker[i] are in range [1, 10^5]
|
class Solution:
def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:
bfb = [0]*max(max(worker),max(difficulty)) # bfb[i] will tell us the best profitting job that is at or below difficulty i+1
for diff,prof in sorted(zip(difficulty,profit)):
bfb[diff-1] = max(bfb[diff-1],prof)
currMax = 0
for i in range(len(bfb)):
bfb[i] = max(currMax,bfb[i])
currMax = bfb[i]
# print(bfb)
total = 0
for w in worker:
total += bfb[w-1]
return total
|
We have jobs: difficulty[i] is the difficulty of the ith job, and profit[i] is the profit of the ith job.
Now we have some workers. worker[i] is the ability of the ith worker, which means that this worker can only complete a job with difficulty at most worker[i].
Every worker can be assigned at most one job, but one job can be completed multiple times.
For example, if 3 people attempt the same job that pays $1, then the total profit will be $3. If a worker cannot complete any job, his profit is $0.
What is the most profit we can make?
Example 1:
Input: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]
Output: 100
Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get profit of [20,20,30,30] seperately.
Notes:
1 <= difficulty.length = profit.length <= 10000
1 <= worker.length <= 10000
difficulty[i], profit[i], worker[i] are in range [1, 10^5]
|
class Solution:
def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:
difficulty_price = sorted(list(zip(difficulty, profit)), key = lambda x: (x[0], x[1]))
max_prices = []
n = -1
curr_price = 0
for i in range(max(difficulty)+1):
if i == difficulty_price[n+1][0]:
n+=1
while n < len(difficulty_price) - 1 and i == difficulty_price[n+1][0]:
n+=1
if difficulty_price[n][1] > curr_price:
curr_price = difficulty_price[n][1]
max_prices.append(curr_price)
profit_sum = 0
for sub_worker in worker:
if sub_worker >= len(max_prices):
profit_sum += max_prices[-1]
else:
profit_sum += max_prices[sub_worker]
return profit_sum
|
We have jobs: difficulty[i] is the difficulty of the ith job, and profit[i] is the profit of the ith job.
Now we have some workers. worker[i] is the ability of the ith worker, which means that this worker can only complete a job with difficulty at most worker[i].
Every worker can be assigned at most one job, but one job can be completed multiple times.
For example, if 3 people attempt the same job that pays $1, then the total profit will be $3. If a worker cannot complete any job, his profit is $0.
What is the most profit we can make?
Example 1:
Input: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]
Output: 100
Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get profit of [20,20,30,30] seperately.
Notes:
1 <= difficulty.length = profit.length <= 10000
1 <= worker.length <= 10000
difficulty[i], profit[i], worker[i] are in range [1, 10^5]
|
class Solution:
def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:
#get best profit by difficulty and apply to each worker
#init memo table
m = max(difficulty)
dp = [0] * m
for d, p in zip(difficulty, profit):
dp[d - 1] = max(dp[d - 1], p)
for i in range(1,len(dp)):
dp[i] = max(dp[i], dp[i - 1])
return sum([dp[min(w - 1, m - 1)] for w in worker])
|
We have jobs: difficulty[i] is the difficulty of the ith job, and profit[i] is the profit of the ith job.
Now we have some workers. worker[i] is the ability of the ith worker, which means that this worker can only complete a job with difficulty at most worker[i].
Every worker can be assigned at most one job, but one job can be completed multiple times.
For example, if 3 people attempt the same job that pays $1, then the total profit will be $3. If a worker cannot complete any job, his profit is $0.
What is the most profit we can make?
Example 1:
Input: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]
Output: 100
Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get profit of [20,20,30,30] seperately.
Notes:
1 <= difficulty.length = profit.length <= 10000
1 <= worker.length <= 10000
difficulty[i], profit[i], worker[i] are in range [1, 10^5]
|
class Solution:
def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:
jobs = list(zip(difficulty, profit))
jobs.sort()
ans = i = best = 0
for skill in sorted(worker):
while i < len(jobs) and skill >= jobs[i][0]:
best = max(best, jobs[i][1])
i += 1
ans += best
return ans
|
We have jobs: difficulty[i] is the difficulty of the ith job, and profit[i] is the profit of the ith job.
Now we have some workers. worker[i] is the ability of the ith worker, which means that this worker can only complete a job with difficulty at most worker[i].
Every worker can be assigned at most one job, but one job can be completed multiple times.
For example, if 3 people attempt the same job that pays $1, then the total profit will be $3. If a worker cannot complete any job, his profit is $0.
What is the most profit we can make?
Example 1:
Input: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]
Output: 100
Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get profit of [20,20,30,30] seperately.
Notes:
1 <= difficulty.length = profit.length <= 10000
1 <= worker.length <= 10000
difficulty[i], profit[i], worker[i] are in range [1, 10^5]
|
class Solution:
def binarySearch(self, l, r, x, li):
if (r - l <= 1):
if (li[r] <= x):
return r
else:
return l
m = (l + r + 1)//2
if (li[m] <= x):
return self.binarySearch(m, r, x, li)
else:
return self.binarySearch(l, m-1, x, li)
def maxProfitAssignment(self, difficulty, profit, worker):
difficulty.append(0)
profit.append(0)
jobs = sorted(zip(difficulty, profit))
J = len(jobs)
jobDifficulty = [j[0] for j in jobs]
mostProfit = [jobs[0][1] for j in jobs]
for i in range(1, J):
mostProfit[i] = max(jobs[i][1], mostProfit[i-1])
totProfit = 0
for w in worker:
maxJob = self.binarySearch(0, J-1, w, jobDifficulty)
totProfit += mostProfit[maxJob]
return totProfit
|
We have jobs: difficulty[i] is the difficulty of the ith job, and profit[i] is the profit of the ith job.
Now we have some workers. worker[i] is the ability of the ith worker, which means that this worker can only complete a job with difficulty at most worker[i].
Every worker can be assigned at most one job, but one job can be completed multiple times.
For example, if 3 people attempt the same job that pays $1, then the total profit will be $3. If a worker cannot complete any job, his profit is $0.
What is the most profit we can make?
Example 1:
Input: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]
Output: 100
Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get profit of [20,20,30,30] seperately.
Notes:
1 <= difficulty.length = profit.length <= 10000
1 <= worker.length <= 10000
difficulty[i], profit[i], worker[i] are in range [1, 10^5]
|
class Solution:
def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:
n = len(profit)
maxm = max(difficulty)
dp = [0]*(1+maxm)
for i in range(n):
dp[difficulty[i]] = max(dp[difficulty[i]],profit[i])
for i in range(1,maxm+1):
dp[i] = max(dp[i],dp[i-1])
ans = 0
for i in worker:
if i > maxm:
ans += dp[maxm]
else:
ans += dp[i]
return ans
|
We have jobs: difficulty[i] is the difficulty of the ith job, and profit[i] is the profit of the ith job.
Now we have some workers. worker[i] is the ability of the ith worker, which means that this worker can only complete a job with difficulty at most worker[i].
Every worker can be assigned at most one job, but one job can be completed multiple times.
For example, if 3 people attempt the same job that pays $1, then the total profit will be $3. If a worker cannot complete any job, his profit is $0.
What is the most profit we can make?
Example 1:
Input: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]
Output: 100
Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get profit of [20,20,30,30] seperately.
Notes:
1 <= difficulty.length = profit.length <= 10000
1 <= worker.length <= 10000
difficulty[i], profit[i], worker[i] are in range [1, 10^5]
|
class Solution:
def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:
max_v = max(max(difficulty), max(worker))
n = len(difficulty)
best = {}
for i in range(n):
d = difficulty[i]
p = profit[i]
if d not in best:
best[d] = p
else:
best[d] = max(best[d], p)
dp = [0] * (max_v + 1)
dp[0] = 0
for i in range (max_v + 1):
p = 0
if i in best:
p = best[i]
dp[i] = max(dp[i - 1], p)
s = 0
for d in worker:
s += dp[d]
return s
|
We have jobs: difficulty[i] is the difficulty of the ith job, and profit[i] is the profit of the ith job.
Now we have some workers. worker[i] is the ability of the ith worker, which means that this worker can only complete a job with difficulty at most worker[i].
Every worker can be assigned at most one job, but one job can be completed multiple times.
For example, if 3 people attempt the same job that pays $1, then the total profit will be $3. If a worker cannot complete any job, his profit is $0.
What is the most profit we can make?
Example 1:
Input: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]
Output: 100
Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get profit of [20,20,30,30] seperately.
Notes:
1 <= difficulty.length = profit.length <= 10000
1 <= worker.length <= 10000
difficulty[i], profit[i], worker[i] are in range [1, 10^5]
|
class Solution:
def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:
dp_dict = dict(list(zip(difficulty, profit)))
l = len(difficulty)
for idx in range(l):
d = difficulty[idx]
if profit[idx] > dp_dict[d]:
dp_dict[d] = profit[idx]
dp_items = sorted(list(dp_dict.items()), key=lambda x: x[0])
darr = [x[0] for x in dp_items]
max_p = 0
parr = list()
for d,p in dp_items:
if p > max_p:
max_p = dp_dict[d]
parr.append(max_p)
ret = 0
def get_nearest(w, arr):
l = len(arr)
if w < arr[0]: return None
if w > arr[-1]: return l-1
def binary_search(w, i, j):
if i >= l or j >= l or w < arr[i] or w > arr[j]:
return None
if w == arr[i]: return i
if w == arr[j]: return j
k = (i + j) // 2
if arr[k] <= w < arr[k + 1]:
return k
prev = binary_search(w, i, k)
return binary_search(w, k + 1, j) if prev is None else prev
return binary_search(w, 0, l - 1)
for w in worker:
floor_idx = get_nearest(w, darr)
if floor_idx is not None:
ret += parr[floor_idx]
return ret
|
We have jobs: difficulty[i] is the difficulty of the ith job, and profit[i] is the profit of the ith job.
Now we have some workers. worker[i] is the ability of the ith worker, which means that this worker can only complete a job with difficulty at most worker[i].
Every worker can be assigned at most one job, but one job can be completed multiple times.
For example, if 3 people attempt the same job that pays $1, then the total profit will be $3. If a worker cannot complete any job, his profit is $0.
What is the most profit we can make?
Example 1:
Input: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]
Output: 100
Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get profit of [20,20,30,30] seperately.
Notes:
1 <= difficulty.length = profit.length <= 10000
1 <= worker.length <= 10000
difficulty[i], profit[i], worker[i] are in range [1, 10^5]
|
from typing import List
import heapq
class Solution:
def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:
# (-profit[i], difficulty[i])组成最小堆
result_profit = 0
profit_minus_min_heap = list()
for i in range(len(profit) ):
heapq.heappush(profit_minus_min_heap, (-profit[i], difficulty[i]) )
worker_minus_min_heap = [-worker[i] for i in range( len(worker) )]
heapq.heapify(worker_minus_min_heap)
while len(worker_minus_min_heap)!=0 and len(profit_minus_min_heap)!=0:
job_profit, job_difficulty = profit_minus_min_heap[0]
job_profit = -job_profit
worker_ability = worker_minus_min_heap[0]
worker_ability = -worker_ability
if worker_ability >= job_difficulty:
result_profit += job_profit
heapq.heappop( worker_minus_min_heap)
else:
heapq.heappop( profit_minus_min_heap)
return result_profit
|
We have jobs: difficulty[i] is the difficulty of the ith job, and profit[i] is the profit of the ith job.
Now we have some workers. worker[i] is the ability of the ith worker, which means that this worker can only complete a job with difficulty at most worker[i].
Every worker can be assigned at most one job, but one job can be completed multiple times.
For example, if 3 people attempt the same job that pays $1, then the total profit will be $3. If a worker cannot complete any job, his profit is $0.
What is the most profit we can make?
Example 1:
Input: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]
Output: 100
Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get profit of [20,20,30,30] seperately.
Notes:
1 <= difficulty.length = profit.length <= 10000
1 <= worker.length <= 10000
difficulty[i], profit[i], worker[i] are in range [1, 10^5]
|
class Solution:
def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:
make=[0]*(10**5)
num=[(difficulty[i],profit[i])for i in range(len(profit))]
num.sort(key=lambda x:x[0])
x=0
while x<len(num):
if x+1<len(num):
if num[x][1]>num[x+1][1]:
num.pop(x+1)
else:x+=1
else:break
for i in range(len(num)):
make[num[i][0]]=num[i][1]
pre=-1
for i in range(len(make)):
if make[i]!=0:
pre=make[i]
elif pre!=-1:
make[i]=pre
## print(make)
ans=0
for w in worker:
ans+=make[w]
return ans
|
We have jobs: difficulty[i] is the difficulty of the ith job, and profit[i] is the profit of the ith job.
Now we have some workers. worker[i] is the ability of the ith worker, which means that this worker can only complete a job with difficulty at most worker[i].
Every worker can be assigned at most one job, but one job can be completed multiple times.
For example, if 3 people attempt the same job that pays $1, then the total profit will be $3. If a worker cannot complete any job, his profit is $0.
What is the most profit we can make?
Example 1:
Input: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]
Output: 100
Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get profit of [20,20,30,30] seperately.
Notes:
1 <= difficulty.length = profit.length <= 10000
1 <= worker.length <= 10000
difficulty[i], profit[i], worker[i] are in range [1, 10^5]
|
class Solution:
def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:
make=[0]*(10**5)
num=[(difficulty[i],profit[i])for i in range(len(profit))]
num.sort(key=lambda x:x[0])
x=0
while x<len(num):
if x+1<len(num):
if num[x][1]>num[x+1][1]:
num.pop(x+1)
else:x+=1
else:break
for i in range(len(num)):
make[num[i][0]]=num[i][1]
pre=-1
for i in range(len(make)):
if make[i]!=0:
pre=make[i]
elif pre!=-1:
make[i]=pre
ans=0
for w in worker:
ans+=make[w]
return ans
|
We have jobs: difficulty[i] is the difficulty of the ith job, and profit[i] is the profit of the ith job.
Now we have some workers. worker[i] is the ability of the ith worker, which means that this worker can only complete a job with difficulty at most worker[i].
Every worker can be assigned at most one job, but one job can be completed multiple times.
For example, if 3 people attempt the same job that pays $1, then the total profit will be $3. If a worker cannot complete any job, his profit is $0.
What is the most profit we can make?
Example 1:
Input: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]
Output: 100
Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get profit of [20,20,30,30] seperately.
Notes:
1 <= difficulty.length = profit.length <= 10000
1 <= worker.length <= 10000
difficulty[i], profit[i], worker[i] are in range [1, 10^5]
|
import numpy as np
class Solution:
def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:
direc = np.zeros((len(profit),2))
direc[:,0] = difficulty
direc[:,1] = profit
direc = direc[direc[:,0].argsort()]
# print(direc)
max_profit = np.array(direc[:,1])
for i in range(1,len(profit)):
if max_profit[i-1] > direc[i,1]:
max_profit[i] = max_profit[i-1]
# print(max_profit)
result = 0
for j in range(len(worker)):
# if worker[j] in difficulty:
# ind = np.searchsorted(direc[:,0],worker[j],side = 'Left')
# else: ind = np.searchsorted(direc[:,0],worker[j],side = 'Left') - 1
ind = np.searchsorted(direc[:,0],worker[j],side = 'Right') - 1
# print(ind,max_profit[ind])
if ind >-1:result += max_profit[ind]
return int(result)
|
Given a string s, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them causing the left and the right side of the deleted substring to concatenate together.
We repeatedly make k duplicate removals on s until we no longer can.
Return the final string after all such duplicate removals have been made.
It is guaranteed that the answer is unique.
Example 1:
Input: s = "abcd", k = 2
Output: "abcd"
Explanation: There's nothing to delete.
Example 2:
Input: s = "deeedbbcccbdaa", k = 3
Output: "aa"
Explanation:
First delete "eee" and "ccc", get "ddbbbdaa"
Then delete "bbb", get "dddaa"
Finally delete "ddd", get "aa"
Example 3:
Input: s = "pbbcggttciiippooaais", k = 2
Output: "ps"
Constraints:
1 <= s.length <= 10^5
2 <= k <= 10^4
s only contains lower case English letters.
|
class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
st=[['*',0]]
for c in s:
if c!=st[-1][0]:
st.append([c,1])
else:
st[-1][1]+=1
if st[-1][1]==k:
st.pop()
res=''
for c,v in st:
res+=c*v
return res
|
Given a string s, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them causing the left and the right side of the deleted substring to concatenate together.
We repeatedly make k duplicate removals on s until we no longer can.
Return the final string after all such duplicate removals have been made.
It is guaranteed that the answer is unique.
Example 1:
Input: s = "abcd", k = 2
Output: "abcd"
Explanation: There's nothing to delete.
Example 2:
Input: s = "deeedbbcccbdaa", k = 3
Output: "aa"
Explanation:
First delete "eee" and "ccc", get "ddbbbdaa"
Then delete "bbb", get "dddaa"
Finally delete "ddd", get "aa"
Example 3:
Input: s = "pbbcggttciiippooaais", k = 2
Output: "ps"
Constraints:
1 <= s.length <= 10^5
2 <= k <= 10^4
s only contains lower case English letters.
|
class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
if not s or k == 0:
return s
stack = [['#', 0]]
for c in s:
if stack[-1][0] == c:
stack[-1][1] += 1
if stack[-1][1] == k:
stack.pop()
else:
stack.append([c, 1])
return ''.join(c*k for c, k in stack)
|
Given a string s, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them causing the left and the right side of the deleted substring to concatenate together.
We repeatedly make k duplicate removals on s until we no longer can.
Return the final string after all such duplicate removals have been made.
It is guaranteed that the answer is unique.
Example 1:
Input: s = "abcd", k = 2
Output: "abcd"
Explanation: There's nothing to delete.
Example 2:
Input: s = "deeedbbcccbdaa", k = 3
Output: "aa"
Explanation:
First delete "eee" and "ccc", get "ddbbbdaa"
Then delete "bbb", get "dddaa"
Finally delete "ddd", get "aa"
Example 3:
Input: s = "pbbcggttciiippooaais", k = 2
Output: "ps"
Constraints:
1 <= s.length <= 10^5
2 <= k <= 10^4
s only contains lower case English letters.
|
class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
res = []
char = s[0]
count = 1
for i in range(1, len(s)):
if s[i] == char:
count += 1
else:
count = 1
char = s[i]
if count == k:
return self.removeDuplicates(s[:i-k+1] + s[i+1:], k)
return s
|
Given a string s, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them causing the left and the right side of the deleted substring to concatenate together.
We repeatedly make k duplicate removals on s until we no longer can.
Return the final string after all such duplicate removals have been made.
It is guaranteed that the answer is unique.
Example 1:
Input: s = "abcd", k = 2
Output: "abcd"
Explanation: There's nothing to delete.
Example 2:
Input: s = "deeedbbcccbdaa", k = 3
Output: "aa"
Explanation:
First delete "eee" and "ccc", get "ddbbbdaa"
Then delete "bbb", get "dddaa"
Finally delete "ddd", get "aa"
Example 3:
Input: s = "pbbcggttciiippooaais", k = 2
Output: "ps"
Constraints:
1 <= s.length <= 10^5
2 <= k <= 10^4
s only contains lower case English letters.
|
class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
if len(s) < k:
return s
# stack=[]
# cnt_stack=[]
# for char in s:
# if not stack or stack[-1] !=char:
# stack.append(char)
# cnt_stack.append(1)
# else:
# cnt_stack[-1] +=1
# if cnt_stack[-1] == k:
# cnt_stack.pop()
# stack.pop()
# return ''.join([stack[i]*cnt_stack[i] for i in range(len(stack))])
stack=[[0,'#']]
for char in s:
if char == stack[-1][1]:
stack[-1][0] +=1
if stack[-1][0] == k:
stack.pop()
else:
stack.append([1,char])
return ''.join(c*k for c,k in stack)
|
Given a string s, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them causing the left and the right side of the deleted substring to concatenate together.
We repeatedly make k duplicate removals on s until we no longer can.
Return the final string after all such duplicate removals have been made.
It is guaranteed that the answer is unique.
Example 1:
Input: s = "abcd", k = 2
Output: "abcd"
Explanation: There's nothing to delete.
Example 2:
Input: s = "deeedbbcccbdaa", k = 3
Output: "aa"
Explanation:
First delete "eee" and "ccc", get "ddbbbdaa"
Then delete "bbb", get "dddaa"
Finally delete "ddd", get "aa"
Example 3:
Input: s = "pbbcggttciiippooaais", k = 2
Output: "ps"
Constraints:
1 <= s.length <= 10^5
2 <= k <= 10^4
s only contains lower case English letters.
|
class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
unique = set(s)
dups = []
for c in unique:
dups.append(c*k)
while True:
start = s
for c in dups:
s = s.replace(c, '')
if start == s:
return s
# ret = list(s)
# while True:
# s = ret
# ret = []
# ac = 1
# for c in s:
# if not ret or ret[-1] != c:
# ac = 1
# ret.append(c)
# else:
# if ac + 1 == k:
# while ac:
# ret.pop()
# ac -= 1
# else:
# ret.append(c)
# ac += 1
# # print(ret, ac)
# if len(ret) == len(s):
# break
# return ''.join(ret)
|
Given a string s, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them causing the left and the right side of the deleted substring to concatenate together.
We repeatedly make k duplicate removals on s until we no longer can.
Return the final string after all such duplicate removals have been made.
It is guaranteed that the answer is unique.
Example 1:
Input: s = "abcd", k = 2
Output: "abcd"
Explanation: There's nothing to delete.
Example 2:
Input: s = "deeedbbcccbdaa", k = 3
Output: "aa"
Explanation:
First delete "eee" and "ccc", get "ddbbbdaa"
Then delete "bbb", get "dddaa"
Finally delete "ddd", get "aa"
Example 3:
Input: s = "pbbcggttciiippooaais", k = 2
Output: "ps"
Constraints:
1 <= s.length <= 10^5
2 <= k <= 10^4
s only contains lower case English letters.
|
class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
lengths = [[None, 0]]
idx = 0
while idx < len(s):
current = lengths[-1][0]
if current == s[idx]:
lengths[-1][1] += 1
else:
lengths.append([s[idx], 1])
current = s[idx]
if lengths[-1][1] == k:
lengths.pop()
s = s[:idx - k + 1] + s[idx + 1:]
idx -= k
idx += 1
return s
|
Given a string s, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them causing the left and the right side of the deleted substring to concatenate together.
We repeatedly make k duplicate removals on s until we no longer can.
Return the final string after all such duplicate removals have been made.
It is guaranteed that the answer is unique.
Example 1:
Input: s = "abcd", k = 2
Output: "abcd"
Explanation: There's nothing to delete.
Example 2:
Input: s = "deeedbbcccbdaa", k = 3
Output: "aa"
Explanation:
First delete "eee" and "ccc", get "ddbbbdaa"
Then delete "bbb", get "dddaa"
Finally delete "ddd", get "aa"
Example 3:
Input: s = "pbbcggttciiippooaais", k = 2
Output: "ps"
Constraints:
1 <= s.length <= 10^5
2 <= k <= 10^4
s only contains lower case English letters.
|
class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
ret = list(s)
while True:
s = ret
ret = []
ac = 1
for c in s:
if not ret or ret[-1] != c:
ac = 1
ret.append(c)
else:
if ac + 1 == k:
while ac:
ret.pop()
ac -= 1
else:
ret.append(c)
ac += 1
# print(ret, ac)
if len(ret) == len(s):
break
return ''.join(ret)
|
Given a string s, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them causing the left and the right side of the deleted substring to concatenate together.
We repeatedly make k duplicate removals on s until we no longer can.
Return the final string after all such duplicate removals have been made.
It is guaranteed that the answer is unique.
Example 1:
Input: s = "abcd", k = 2
Output: "abcd"
Explanation: There's nothing to delete.
Example 2:
Input: s = "deeedbbcccbdaa", k = 3
Output: "aa"
Explanation:
First delete "eee" and "ccc", get "ddbbbdaa"
Then delete "bbb", get "dddaa"
Finally delete "ddd", get "aa"
Example 3:
Input: s = "pbbcggttciiippooaais", k = 2
Output: "ps"
Constraints:
1 <= s.length <= 10^5
2 <= k <= 10^4
s only contains lower case English letters.
|
class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
count = 1
flag = 1
last_idx = 0
while(1):
i = 0
temp_s = s
while(i < len(s)-1):
#print(\"i = \",i)
#print(\"s = \",s)
if(s[i] != s[i+1]):
i = i+1
else:
last_idx = i
while(1):
if(i+1 == len(s)):
break
elif(s[i] == s[i+1]):
count = count+1
i = i+1
else:
break
if(count >= k):
s = s[:last_idx] + s[last_idx+k:]
i = last_idx
count = 1
if(temp_s == s):
break
return s
|
Given a string s, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them causing the left and the right side of the deleted substring to concatenate together.
We repeatedly make k duplicate removals on s until we no longer can.
Return the final string after all such duplicate removals have been made.
It is guaranteed that the answer is unique.
Example 1:
Input: s = "abcd", k = 2
Output: "abcd"
Explanation: There's nothing to delete.
Example 2:
Input: s = "deeedbbcccbdaa", k = 3
Output: "aa"
Explanation:
First delete "eee" and "ccc", get "ddbbbdaa"
Then delete "bbb", get "dddaa"
Finally delete "ddd", get "aa"
Example 3:
Input: s = "pbbcggttciiippooaais", k = 2
Output: "ps"
Constraints:
1 <= s.length <= 10^5
2 <= k <= 10^4
s only contains lower case English letters.
|
class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
while True:
stk = []
s_new = []
for c in s:
if len(stk)==k: stk=[]
while stk and c!=stk[-1]:
s_new.append(stk.pop())
stk.append(c)
if len(stk)==k: stk=[]
while stk:
s_new.append(stk.pop())
print(''.join(s_new))
if s==s_new: break
s = s_new
return ''.join(s)
|
Given a string s, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them causing the left and the right side of the deleted substring to concatenate together.
We repeatedly make k duplicate removals on s until we no longer can.
Return the final string after all such duplicate removals have been made.
It is guaranteed that the answer is unique.
Example 1:
Input: s = "abcd", k = 2
Output: "abcd"
Explanation: There's nothing to delete.
Example 2:
Input: s = "deeedbbcccbdaa", k = 3
Output: "aa"
Explanation:
First delete "eee" and "ccc", get "ddbbbdaa"
Then delete "bbb", get "dddaa"
Finally delete "ddd", get "aa"
Example 3:
Input: s = "pbbcggttciiippooaais", k = 2
Output: "ps"
Constraints:
1 <= s.length <= 10^5
2 <= k <= 10^4
s only contains lower case English letters.
|
class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
ns = []
deleted= True
while deleted:
deleted = False
i = 0
ns = []
while i < len(s):
if i <= len(s) - k and s[i+1:i+k] == s[i]*(k-1):
deleted = True
i += k
else:
ns.append(s[i])
i += 1
s = ''.join(ns)
return s
|
Given a string s, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them causing the left and the right side of the deleted substring to concatenate together.
We repeatedly make k duplicate removals on s until we no longer can.
Return the final string after all such duplicate removals have been made.
It is guaranteed that the answer is unique.
Example 1:
Input: s = "abcd", k = 2
Output: "abcd"
Explanation: There's nothing to delete.
Example 2:
Input: s = "deeedbbcccbdaa", k = 3
Output: "aa"
Explanation:
First delete "eee" and "ccc", get "ddbbbdaa"
Then delete "bbb", get "dddaa"
Finally delete "ddd", get "aa"
Example 3:
Input: s = "pbbcggttciiippooaais", k = 2
Output: "ps"
Constraints:
1 <= s.length <= 10^5
2 <= k <= 10^4
s only contains lower case English letters.
|
class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
def helper(s):
ans = []
i = 0
while i < len(s):
if s[i] * k != s[i:i+k]:
ans.append(s[i])
i += 1
else:
i += k
if len(ans) == len(s):
res.append(''.join(ans))
return
else:
helper(''.join(ans))
res = []
helper(s)
return res[0]
|
Given a string s, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them causing the left and the right side of the deleted substring to concatenate together.
We repeatedly make k duplicate removals on s until we no longer can.
Return the final string after all such duplicate removals have been made.
It is guaranteed that the answer is unique.
Example 1:
Input: s = "abcd", k = 2
Output: "abcd"
Explanation: There's nothing to delete.
Example 2:
Input: s = "deeedbbcccbdaa", k = 3
Output: "aa"
Explanation:
First delete "eee" and "ccc", get "ddbbbdaa"
Then delete "bbb", get "dddaa"
Finally delete "ddd", get "aa"
Example 3:
Input: s = "pbbcggttciiippooaais", k = 2
Output: "ps"
Constraints:
1 <= s.length <= 10^5
2 <= k <= 10^4
s only contains lower case English letters.
|
class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
sliced = True
while sliced == True:
s, sliced = self.getSlices(s, k)
return s
def getSlices(self, s, k):
sliced = False
idx = set()
i = 0
while i < len(s):
if s[i]*k == s[i:i+k]:
idx.update(range(i, i+k))
sliced = True
i += k
i += 1
if sliced:
new_str = ''.join([char for i, char in enumerate(s) if i not in idx])
return new_str, sliced
return s, sliced
|
Given a string s, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them causing the left and the right side of the deleted substring to concatenate together.
We repeatedly make k duplicate removals on s until we no longer can.
Return the final string after all such duplicate removals have been made.
It is guaranteed that the answer is unique.
Example 1:
Input: s = "abcd", k = 2
Output: "abcd"
Explanation: There's nothing to delete.
Example 2:
Input: s = "deeedbbcccbdaa", k = 3
Output: "aa"
Explanation:
First delete "eee" and "ccc", get "ddbbbdaa"
Then delete "bbb", get "dddaa"
Finally delete "ddd", get "aa"
Example 3:
Input: s = "pbbcggttciiippooaais", k = 2
Output: "ps"
Constraints:
1 <= s.length <= 10^5
2 <= k <= 10^4
s only contains lower case English letters.
|
class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
while True:
stk = []
s_new = []
for c in s:
if len(stk)==k: stk=[]
while stk and c!=stk[-1]:
s_new.append(stk.pop())
stk.append(c)
if len(stk)==k: stk=[]
while stk:
s_new.append(stk.pop())
if s==s_new: break
s = s_new
return ''.join(s)
|
Given a string s, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them causing the left and the right side of the deleted substring to concatenate together.
We repeatedly make k duplicate removals on s until we no longer can.
Return the final string after all such duplicate removals have been made.
It is guaranteed that the answer is unique.
Example 1:
Input: s = "abcd", k = 2
Output: "abcd"
Explanation: There's nothing to delete.
Example 2:
Input: s = "deeedbbcccbdaa", k = 3
Output: "aa"
Explanation:
First delete "eee" and "ccc", get "ddbbbdaa"
Then delete "bbb", get "dddaa"
Finally delete "ddd", get "aa"
Example 3:
Input: s = "pbbcggttciiippooaais", k = 2
Output: "ps"
Constraints:
1 <= s.length <= 10^5
2 <= k <= 10^4
s only contains lower case English letters.
|
class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
len_s = len(s)
if k > len_s:
return s
def helper(string, itr_range):
not_found = False #if no k repeating elements found, then True
while not not_found:
not_found = True
for i in range(itr_range):
if string[i:i+k] == string[i]*k:
string = string[:i]+string[i+k:]
itr_range = len(string)-k+1
not_found = False
break
return string
return helper(s, len_s-k+1)
|
Given a string s, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them causing the left and the right side of the deleted substring to concatenate together.
We repeatedly make k duplicate removals on s until we no longer can.
Return the final string after all such duplicate removals have been made.
It is guaranteed that the answer is unique.
Example 1:
Input: s = "abcd", k = 2
Output: "abcd"
Explanation: There's nothing to delete.
Example 2:
Input: s = "deeedbbcccbdaa", k = 3
Output: "aa"
Explanation:
First delete "eee" and "ccc", get "ddbbbdaa"
Then delete "bbb", get "dddaa"
Finally delete "ddd", get "aa"
Example 3:
Input: s = "pbbcggttciiippooaais", k = 2
Output: "ps"
Constraints:
1 <= s.length <= 10^5
2 <= k <= 10^4
s only contains lower case English letters.
|
class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
if len(s)<k:
return s
found = self.findStr(s, k)
if not found:
return s
else:
return self.removeDuplicates(s.replace(found, ''), k)
def findStr(self, s:str, k:int):
for i in range(len(s)):
if (s[i]*k) in s:
return s[i]*k
return None
|
Given a string s, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them causing the left and the right side of the deleted substring to concatenate together.
We repeatedly make k duplicate removals on s until we no longer can.
Return the final string after all such duplicate removals have been made.
It is guaranteed that the answer is unique.
Example 1:
Input: s = "abcd", k = 2
Output: "abcd"
Explanation: There's nothing to delete.
Example 2:
Input: s = "deeedbbcccbdaa", k = 3
Output: "aa"
Explanation:
First delete "eee" and "ccc", get "ddbbbdaa"
Then delete "bbb", get "dddaa"
Finally delete "ddd", get "aa"
Example 3:
Input: s = "pbbcggttciiippooaais", k = 2
Output: "ps"
Constraints:
1 <= s.length <= 10^5
2 <= k <= 10^4
s only contains lower case English letters.
|
class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
distinct = len(set(s))
while len(s) >= k:
new_s = ''
cur, count = s[0], 1
for i in range(1, len(s)):
print(cur, count)
if s[i] == cur:
count += 1
else:
new_s += cur * (count % k)
cur, count = s[i], 1
new_s += cur * (count % k)
if s == new_s:
break
s = new_s
return s
|
Given a string s, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them causing the left and the right side of the deleted substring to concatenate together.
We repeatedly make k duplicate removals on s until we no longer can.
Return the final string after all such duplicate removals have been made.
It is guaranteed that the answer is unique.
Example 1:
Input: s = "abcd", k = 2
Output: "abcd"
Explanation: There's nothing to delete.
Example 2:
Input: s = "deeedbbcccbdaa", k = 3
Output: "aa"
Explanation:
First delete "eee" and "ccc", get "ddbbbdaa"
Then delete "bbb", get "dddaa"
Finally delete "ddd", get "aa"
Example 3:
Input: s = "pbbcggttciiippooaais", k = 2
Output: "ps"
Constraints:
1 <= s.length <= 10^5
2 <= k <= 10^4
s only contains lower case English letters.
|
class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
duplicates=[k*i for i in 'abcdefghijklmnopqrstuvwxyz']
counter=0
while counter!=len(s):
counter=len(s)
for i in duplicates:
s=s.replace(i,'')
return s
|
Given a string s, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them causing the left and the right side of the deleted substring to concatenate together.
We repeatedly make k duplicate removals on s until we no longer can.
Return the final string after all such duplicate removals have been made.
It is guaranteed that the answer is unique.
Example 1:
Input: s = "abcd", k = 2
Output: "abcd"
Explanation: There's nothing to delete.
Example 2:
Input: s = "deeedbbcccbdaa", k = 3
Output: "aa"
Explanation:
First delete "eee" and "ccc", get "ddbbbdaa"
Then delete "bbb", get "dddaa"
Finally delete "ddd", get "aa"
Example 3:
Input: s = "pbbcggttciiippooaais", k = 2
Output: "ps"
Constraints:
1 <= s.length <= 10^5
2 <= k <= 10^4
s only contains lower case English letters.
|
class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
if not s:
return ''
stack = []
prev = count = None
for i in range(0, len(s)):
if not prev:
prev, count = s[i], 1
elif s[i] == prev:
count += 1
else:
stack.append((prev, count))
prev = s[i]
count = 1
if count == k:
if stack:
prev, count = stack.pop()
else:
prev = None
# print(stack, s[i], i, prev, count)
stack.append((prev, count))
output = ''
for e,c in stack:
output += e*c
return output
'''
#check k = 1
'''
|
Given a string s, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them causing the left and the right side of the deleted substring to concatenate together.
We repeatedly make k duplicate removals on s until we no longer can.
Return the final string after all such duplicate removals have been made.
It is guaranteed that the answer is unique.
Example 1:
Input: s = "abcd", k = 2
Output: "abcd"
Explanation: There's nothing to delete.
Example 2:
Input: s = "deeedbbcccbdaa", k = 3
Output: "aa"
Explanation:
First delete "eee" and "ccc", get "ddbbbdaa"
Then delete "bbb", get "dddaa"
Finally delete "ddd", get "aa"
Example 3:
Input: s = "pbbcggttciiippooaais", k = 2
Output: "ps"
Constraints:
1 <= s.length <= 10^5
2 <= k <= 10^4
s only contains lower case English letters.
|
class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
stack = [['#', 0]]
for c in s:
if stack[-1][0] == c:
stack[-1][1] += 1
if stack[-1][1] == k:
stack.pop()
else:
stack.append([c, 1])
return ''.join(c * k for c, k in stack)
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
biggest = A[0]
newbiggest = A[0]
lenL = 1
total = 1
for itr in A[1:]:
total += 1
if itr < biggest:
lenL = total
biggest = newbiggest
else:
if itr > newbiggest:
newbiggest = itr
return lenL
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
res = 0
v = A[0]
max_sofar = v
for i in range(len(A)):
max_sofar = max(max_sofar, A[i])
if A[i] < v:
v = max_sofar
res = i
return res+1
# 如果中间有一个数字变大,我不更新v, v只是之前最大的数
# [32,57,24,19,0,24,49,67,87,87] 如果我不更新v,32 会一直最大,那么49 就归在右边了
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
a = [A[0]]
b = [0 for i in range(len(A))]
for i in range(1, len(A)):
a.append(max(a[i - 1], A[i]))
b[-1] = A[-1]
for i in range(len(A) - 2, -1, -1):
b[i] = min(b[i + 1], A[i])
for i in range(len(A) - 1):
if a[i] <= b[i + 1]:
return i + 1
return -1
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
n = len(A)
mini = [float('-inf')]*n
maxi = [float('inf')]*n
mini[0] = A[0]
maxi[n - 1] = A[n - 1]
for i in range(1, n):
mini[i] = max(mini[i - 1], A[i])
for i in range(n-2, -1, -1):
maxi[i] = min(maxi[i + 1], A[i])
# print(mini)
# print(maxi)
for i in range(n - 1):
if mini[i] <= maxi[i + 1]:
return i + 1
return 0
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
N = len(A)
maxleft = [None] * N
minright = [None] * N
m = A[0]
for i in range(N):
m = max(m, A[i])
maxleft[i] = m
m = A[-1]
for i in range(N -1, -1, -1):
m = min(m, A[i])
minright[i] = m
for i in range(1, N):
if maxleft[i-1] <= minright[i]:
return i
# # https://leetcode.com/problems/partition-array-into-disjoint-intervals/discuss/175904/Explained-Python-simple-O(N)-time-O(1)-space
# # The idea is, v is nothing but the max value of the left half and max_so_far is a nonlocal maximum of the entire array. So by selecting elements only lesser than max of left side (v), we set V to the first element.
# disjoint = 0
# v = A[disjoint]
# max_so_far = v
# for i in range(len(A)):
# max_so_far = max(max_so_far, A[i])
# if A[i] < v:
# disjoint = i
# v = max_so_far
# return disjoint + 1
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
n = len(A)
large = [0] * n
small = [0] * n
l, s = -sys.maxsize, sys.maxsize
for i in range(n):
l = max(l, A[i])
s = min(s, A[n-1-i])
large[i] = l
small[n-1-i] = s
for i in range(n):
if large[i] <= small[i+1]: return i+1
return -1
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
left = [A[0]]
for i in range(1, len(A)):
left.append(max(left[-1], A[i]))
right = [A[-1]]
for i in range(len(A) - 2, -1, -1):
right.append(min(right[-1], A[i]))
for i in range(1, len(A)):
if left[i - 1] <= right[-i - 1]:
return i
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
n = len(A)
left = [0 for i in range(n)]
right = [0 for i in range(n)]
left[0], right[n-1] = A[0], A[n-1]
for i in range(1, n):
left[i] = max(left[i-1], A[i])
for i in range(n-2, -1, -1):
right[i] = min(right[i+1], A[i])
print(left, right)
for i in range(n-1):
if left[i] <= right[i+1]:
return i+1
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
run_max = [float('-inf')]
run_min = [float('inf')]
# get run_max
p = 1
while p < len(A):
run_max.append(max(run_max[-1], A[p-1]))
p += 1
# get run_min
p = len(A) - 2
while p > -1:
run_min.append(min(run_min[-1], A[p+1]))
p -= 1
run_min = run_min[::-1]
# find the pos that satisfies the condition.
res = -1
p = 0
done = False
while p < len(A) - 1 and not done:
if A[p] <= run_min[p] and run_max[p] <= run_min[p]:
res = p + 1
done = True
p += 1
return res
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
left_max = []
right_min = []
for i in range(len(A)):
if i == 0:
left_max.append(A[i])
else:
left_max.append(max(A[i], left_max[-1]))
for i in range(len(A)-1, -1, -1):
if i == len(A) - 1:
right_min.append(A[i])
else:
right_min.append(min(A[i], right_min[-1]))
right_min.reverse()
for i in range(len(A)-1):
lm = left_max[i]
rm = right_min[i+1]
if lm <= rm:
return i+1
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
n = len(A)
max_left, min_right = [None]*n, [None]*n
max_left[0] = A[0]
for i in range(1, n):
max_left[i] = max(max_left[i-1], A[i])
min_right[-1] = A[-1]
for i in range(n-2, -1, -1):
min_right[i] = min(min_right[i+1], A[i])
for i in range(1, n):
if max_left[i-1] <= min_right[i]:
return i
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
l, r = 0, len(A) - 1
leftMax = A[l]
rightMin = A[r]
minHash = {}
while l < r:
leftMax = max(leftMax, A[l])
rightMin = min(rightMin, A[r])
if rightMin >= leftMax:
r -= 1
else:
l += 1
for i in range(r, len(A)):
if A[i] not in minHash:
minHash[A[i]] = []
minHash[A[i]].append(i)
minHash = sorted(list(minHash.items()), key=lambda x: x[0])
#print (leftMax, rightMin, minHash)
i, res = 0, 1
while i < len(minHash) and minHash[i][0] < leftMax:
positions = minHash[i][1]
res = max(positions[-1]+1, res)
i += 1
return res
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
mx=[-1]*len(A)
mn=[-1]*len(A)
for i in range(len(A)):
if i==0:
mx[i]=A[i]
else:
mx[i]=max(A[i],mx[i-1])
for j in range(len(A)-1,-1,-1):
if j==len(A)-1:
mn[j]=A[j]
else:
mn[j]=min(A[j],mn[j+1])
#print(mx,mn)
for i in range(len(A)-1):
#print(mx[i],mn[i+1])
if mx[i]<=mn[i+1]:
#print('yo')
return i+1
return len(A)-1
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
n = len(A)
memo = [[0 for _ in range(n)] for _ in range(2)]
left, right = 0, (1<<31)-1
i, j = 0, n-1
while i < n and j >= 0:
right = min(right, A[j])
left = max(left, A[i])
memo[0][i] = left
memo[1][j] = right
i += 1
j -= 1
i, j = 0, 1
while j < n and memo[0][i] > memo[1][j]:
i, j = i+1, j+1
return j
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
from collections import Counter
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
c = Counter(A)
d = Counter()
keys = sorted(c.keys())
d[keys[0]] = 0
for i in range(1, len(keys)):
d[keys[i]] = c[keys[i-1]] + d[keys[i-1]]
lesscount, mx = 0, -float('inf')
equal = 0
for i in range(len(A)):
# mx = max(mx, A[i])
if A[i] < mx:
lesscount += 1
elif A[i] == mx:
equal += 1
else:
mx = A[i]
lesscount += equal
equal = 1
# print(A[i], mx, lesscount, equal, d[mx])
if lesscount == d[mx]:
return i + 1
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
left = [0 for i in range(len(A))]
left[0] = A[0]
for i in range(1, len(A)):
left[i] = max(left[i-1], A[i])
right = [0 for i in range(len(A))]
right[-1] = A[-1]
for i in reversed(range(len(A)-1)):
right[i] = min(right[i+1], A[i])
for i in range(len(A)-1):
if left[i] <= right[i+1]:
return i+1
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
N = len(A)
maxLeft = dict()
minRight = dict()
if N == 2 and A[0] <= A[1]:
return 1
maxLeft[0] = A[0]
for i in range(1, N - 1):
maxLeft[i] = max(maxLeft[i - 1], A[i])
minRight[N - 1] = A[-1]
for i in range(N - 2, 0, -1):
minRight[i] = min(minRight[i + 1], A[i])
print({ 'maxLeft': maxLeft })
print({ 'minRight': minRight })
for i in range(N - 1):
if maxLeft[i] <= minRight[i + 1]:
return i + 1
return -1
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
mx=[-1]*len(A)
mn=[-1]*len(A)
for i in range(len(A)):
if i==0:
mx[i]=A[i]
else:
mx[i]=max(A[i],mx[i-1])
for j in range(len(A)-1,-1,-1):
if j==len(A)-1:
mn[j]=A[j]
else:
mn[j]=min(A[j],mn[j+1])
#print(mx,mn)
for i in range(len(A)-1):
print(mx[i],mn[i+1])
if mx[i]<=mn[i+1]:
#print('yo')
return i+1
return len(A)-1
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
length = len(A)
leftMax = A[0]
currMax = leftMax
ret = 0
for i in range(1, length):
currMax = max(A[i], currMax)
if leftMax > A[i]:
leftMax = currMax
ret = i
return ret + 1
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
maxval = A[0]
v = A[0]
disjoint = 0
for i in range(len(A)):
maxval = max(maxval,A[i])
if A[i]<v:
disjoint = i
v = maxval
return disjoint+1
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
split_index = 0
local_max = A[0]
max_num = local_max
for i in range(len(A)):
if A[i] < local_max:
split_index = i
local_max = max_num
else:
max_num = max(max_num,A[i])
return split_index + 1
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
minA=[A[0],]
for i in A[1:]:
minA.append(max(i,minA[-1]))
minB=[A[-1],]
for i in A[:-1][::-1]:
minB.append(min(minB[-1],i))
minB=minB[::-1]
for i in range(1,len(A)):
if minA[i-1]<=minB[i]:
return i
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
max_left = float('-inf')
min_right = A[-1]
left = []
right = [A[-1]]
for i in range(len(A)):
max_left = max(max_left, A[i])
left.append(max_left)
for i in range(len(A) - 2, -1, -1):
min_right = min(min_right, A[i + 1])
right.append(min_right)
right.reverse()
#print(left)
#print(right)
for i in range(len(left)):
if left[i] <= right[i]:
return i + 1
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
left = [0]*len(A)
for i in range(len(A)):
if i == 0:
left[i] = A[i]
else:
if A[i] > left[i-1]:
left[i] = A[i]
else:
left[i] = left[i-1]
A_reversed = A[::-1]
right = [0]*len(A)
for i in range(len(A)):
if i == 0:
right[i] = A_reversed[i]
else:
if A_reversed[i] < right[i-1]:
right[i] = A_reversed[i]
else:
right[i] = right[i-1]
right = right[::-1]
print(left, right)
for i in range(len(left)-1):
if left[i] <= right[i+1]:
return i+1
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
n = len(A)
d = [0] * n
d[n-1] = A[n-1]
for i in range(len(A)-2,-1,-1):
d[i] = min(A[i],d[i+1])
# print(d)
mx = A[0]
for i in range(1,n):
if mx <= d[i]:
return i
else:
mx = max(mx,A[i])
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
least = [float('inf')] * len(A)
for i in range(len(A)-1, -1, -1):
if i == len(A) - 1:
least[i] = A[i]
else:
least[i] = min(least[i+1], A[i])
greatest = A[0]
for i in range(1, len(A)):
if greatest <= least[i]:
break
greatest = max(greatest, A[i])
return i
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
l = [0] * len(A)
r = [0] * len(A)
for i in range(len(l)):
l[i] = max(A[i],l[i-1])
r[-1] = A[-1]
for i in range(len(r)-2,-1,-1):
r[i] = min(A[i],r[i+1])
print(l)
print(r)
for i in range(len(l)):
if l[i] <= r[i+1]:
return i+1
return len(l)
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
ans = 1
all_max = A[0]
curr_max = 0
for i in range(len(A)):
curr_max = max(curr_max, A[i])
if all_max > A[i]:
all_max = curr_max
ans = i + 1
return ans
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
'''
[5,0,3,8,6]
mn=[5,0,0,0]
mx=[5,5,5,8,8]
[1,1,1,0,6,12]
mx=[1,1,1,1,6,12]
'''
ml=0
mx=-1e9
mxsofar=1e9
for i,a in enumerate(A):
mx=max(a,mx)
if a<mxsofar:
ml=i+1
mxsofar=mx
#print(\"a=%d,mx=%d,mxsofar %d\"%(a,mx,mxsofar))
return ml
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
right = 1
maxLeft = A[0]
sortedRight = sorted(range(right, len(A)), key=lambda k: A[k])
while A[sortedRight[0]] < maxLeft:
right = sortedRight[0] + 1
maxLeft = max(A[:right])
sortedRight = sorted(range(right, len(A)), key=lambda k: A[k])
return right
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
left = [0]*len(A)
left[0] = A[0]
for i in range(1,len(A)):
left[i] = max(A[i],left[i-1])
right = [0]*len(A)
right[-1] = A[-1]
for i in range(len(A)-2,-1,-1):
right[i] = min(A[i],right[i+1])
print((*left))
print((*right))
for i in range(1, len(A)):
if right[i] >= left[i-1]:
return i
# N = len(A)
# maxleft = [None] * N
# minright = [None] * N
# m = A[0]
# for i in range(N):
# m = max(m, A[i])
# maxleft[i] = m
# m = A[-1]
# for i in range(N-1, -1, -1):
# m = min(m, A[i])
# minright[i] = m
# print(*maxleft)
# print(*minright)
# for i in range(1, N):
# if maxleft[i-1] <= minright[i]:
# return i
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
# O(N**2) with sapce O(1)
n = len(A)
# O(n) with space O(n)
m = n - 1
left_max = [0] * m
left_max[0] = A[0]
right_min = [0] * m
right_min[-1] = A[-1]
for i in range(1,n-1):
left_max[i] = max(left_max[i-1], A[i])
for i in reversed(range(1,m)):
right_min[i-1] = min(right_min[i], A[i])
for i in range(m):
if left_max[i] <= right_min[i]:
return i + 1
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
# O(N**2) with sapce O(1)
n = len(A)
# O(n) with space O(n)
m = n - 1
left_max = [0] * m
left_max[0] = A[0]
right_min = [0] * m
right_min[-1] = A[-1]
for i in range(1,n-1):
left_max[i] = max(left_max[i-1], A[i])
for i in reversed(range(1,m)):
right_min[i-1] = min(right_min[i], A[i])
print(left_max)
print(right_min)
for i in range(m):
if left_max[i] <= right_min[i]:
return i + 1
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
bound = r = 0
gmax = lmax = A[0]
while r < len(A):
if A[r] >= gmax:
lmax = max(lmax, A[r])
r += 1
else:
bound = r
gmax = max(gmax, lmax)
r += 1
return bound+1
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
h = {}
right = float('inf')
for j in range(len(A)-1,-1,-1):
right = min(right, A[j])
h[j] = right
left = float('-inf')
for i in range(len(A)-1):
left = max(left, A[i])
if left <= h[i+1]:
return i + 1
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
cnt = collections.Counter(A)
cur = 0
minn = min(cnt.keys())
for i in range(len(A)):
cur = max(cur, A[i])
cnt[A[i]] -= 1
if cnt[A[i]] == 0:
del cnt[A[i]]
if minn == A[i]:
minn = min(cnt.keys())
if minn >= cur:
return i + 1
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
l = [A[0]]
r = [A[-1]]
for i, v in enumerate(A):
if i == 0:
continue
l.append(max(l[i-1], A[i]))
r.append(min(r[i-1], A[len(A) - i - 1]))
r.reverse()
for i in range(1, len(l)):
if l[i-1] <= r[i]:
return i
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
n = len(A)
partidx = 0
left_max = A[0]
seen_max = A[0]
for i in range(1, n):
seen_max = max(seen_max, A[i])
if A[i] < left_max:
partidx = i
left_max = seen_max
return partidx + 1
# left = [0 for i in range(n)]
# right = [0 for i in range(n)]
# left[0], right[n-1] = A[0], A[n-1]
# for i in range(1, n):
# left[i] = max(left[i-1], A[i])
# for i in range(n-2, -1, -1):
# right[i] = min(right[i+1], A[i])
# print(left, right)
# for i in range(n-1):
# if left[i] <= right[i+1]:
# return i+1
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
i = 1
l_max = A[i-1]
r_min = min(A[i:])
while l_max > r_min:
i += 1
l_max = max(l_max, A[i-1])
if A[i-1] == r_min:
r_min = min(A[i:])
return i
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
n = len(A)
ma = [0] * n
mi = [0] * n
mi[-1] = A[-1]
for i in range(n-2, -1, -1):
mi[i] = min(A[i+1], mi[i+1])
ma[0] = A[0]
for i in range(1, n):
ma[i] = max(A[i], ma[i-1])
# print(mi)
# print(ma)
for i in range(n-1):
if mi[i] >= ma[i]:
return i + 1
return n
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
max_left = [None] * len(A)
min_right = [None] * len(A)
m = A[0]
for i in range(len(A)):
m = max(m, A[i])
max_left[i] = m
m = A[-1]
for i in range(len(A)-1, -1, -1):
m = min(m, A[i])
min_right[i] = m
for i in range(1, len(A)):
if max_left[i-1] <= min_right[i]:
return i
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
max_left = list()
min_right = list()
for i in range(len(A)):
left = A[i]
if i == 0:
max_left.append(left)
elif max_left[i-1] > left:
max_left.append(max_left[i-1])
else:
max_left.append(left)
right = A[len(A) - 1 - i]
if i == 0:
min_right.append(right)
elif min_right[i-1] < right:
min_right.append(min_right[i-1])
else:
min_right.append(right)
for i in range(len(A)):
if max_left[i] <= min_right[len(A) - i - 2]:
return i+1
return 0
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
p = [None]*len(A)
q = [None]*len(A)
for i,v in enumerate(A):
if i == 0:
p[0] = v
else:
p[i] = max(p[i-1],v)
for i,v in enumerate(reversed(A)):
if i == 0:
q[len(A)-1] = v
else:
q[len(A)-1-i] = min(q[len(A)-i],v)
# print(p,q)
for i in range(len(A)-1):
if p[i] <= q[i+1]:
return i+1
return len(A)
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
from sortedcontainers import SortedList
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
left, right = SortedList(), SortedList(A)
for i in range(len(A)-1):
left.add(A[i])
right.discard(A[i])
if left[-1] <= right[0]:
break
return i + 1
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
i = 1
l_max = A[i-1]
d = Counter(A[i:])
a_dict = OrderedDict(sorted(d.items()))
r_min = next(iter(a_dict.items()))[0]
while l_max > r_min:
i += 1
l_max = max(l_max, A[i-1])
if a_dict[A[i-1]] > 1:
a_dict[A[i-1]] -= 1
else:
del a_dict[A[i-1]]
r_min = next(iter(a_dict.items()))[0]
return i
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
# n^2 time to look at all subarrays
# n time to iterate backwards ?
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
min_right = min(A)
max_left = 0
min_from_right = []
current_min_right = A[-1]
for i in range(len(A) - 1, -1, -1):
current_min_right = min(A[i], current_min_right)
min_from_right.insert(0, current_min_right)
for i in range(len(A)):
current = A[i]
max_left = max(max_left, current)
min_right = min_from_right[i + 1] if i < len(A) else 0
if max_left <= min_right:
return i + 1
# def check_partitions(a, b):
# max_a = 0
# for num in a:
# max_a = max(max_a, num)
# min_b = maxsize
# for num in b:
# min_b = min(min_b, num)
# if max_a <= min_b and len(a) > 0 and len(b) > 0:
# return len(a)
# return -1
# min_left = maxsize
# for i in range(1, len(A) + 1):
# cand = check_partitions(A[0:i], A[i: len(A)])
# if cand != -1:
# min_left = min(min_left, cand)
# return min_left
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
maxlefts = []
minrights = []
m = A[0]
for n in A:
m = max(m, n)
maxlefts.append(m)
m = A[len(A) - 1]
for n in A[::-1]:
m = min(m, n)
minrights.insert(0, m)
for i in range(1, len(A)):
if maxlefts[i - 1] <= minrights[i]: return i
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
res = 0
v = A[0]
max_sofar = v
for i in range(len(A)):
max_sofar = max(max_sofar, A[i])
if A[i] < v:
v = max_sofar
res = i
return res+1
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
# biggest = A[0]
# newbiggest = A[0]
# lenL = 1
# total = 1
# for itr in A[1:]:
# total += 1
# if itr < biggest:
# lenL = total
# biggest = newbiggest
# else:
# if itr > newbiggest:
# newbiggest = itr
# return lenL
disjoint = 0
v = A[disjoint]
max_so_far = v
for i in range(len(A)):
max_so_far = max(max_so_far, A[i])
if A[i] < v:
disjoint = i
v = max_so_far
return disjoint + 1
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
n = len(A)
mins = [float('inf')]*(n-1)+[A[-1]]
for i in range(n-2, -1, -1):
mins[i] = min(A[i], mins[i+1])
maxi = 0
for i in range(n-1):
maxi = max(maxi, A[i])
if maxi<=mins[i+1]:
return i+1
return -1
|
Given an array A, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]
Example 2:
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition A as described.
|
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
left_maxes = A[:]
right_mins = A[:]
for i in range(1, len(left_maxes)):
if left_maxes[i] < left_maxes[i - 1]:
left_maxes[i] = left_maxes[i - 1]
for i in range(len(right_mins) - 2, -1, -1):
if right_mins[i] > right_mins[i + 1]:
right_mins[i] = right_mins[i + 1]
for i in range(1, len(A)):
if left_maxes[i - 1] <= right_mins[i]:
return i
|
A password is considered strong if below conditions are all met:
It has at least 6 characters and at most 20 characters.
It must contain at least one lowercase letter, at least one uppercase letter, and at least one digit.
It must NOT contain three repeating characters in a row ("...aaa..." is weak, but "...aa...a..." is strong, assuming other conditions are met).
Write a function strongPasswordChecker(s), that takes a string s as input, and return the MINIMUM change required to make s a strong password. If s is already strong, return 0.
Insertion, deletion or replace of any one character are all considered as one change.
|
class Solution:
def strongPasswordChecker(self, s):
"""
:type s: str
:rtype: int
"""
def length_requirement(password):
length = len(password)
# positive means addition, negative means deletion
if length < 6:
return 6 - length
elif length > 20:
return 20 - length
else:
return 0
def category_requirement(password):
# input
string = set(password)
lowercase = set('qwertyuiopasdfghjklzxcvbnm')
uppercase = set('QWERTYUIOPASDFGHJKLZXCVBNM')
digit = set('1234567890')
condition = [lowercase, uppercase, digit]
# output positive for addition
missing = 0
for s in condition:
if not s & string:
missing += 1
return missing
def repeat_requirement(password):
# store the repeated character and counts its occurrence
count = 1
repeat = None
weak_pair = []
for c in password:
if c == repeat:
# the same character
count += 1
else:
# new character
if count >= 3:
weak_pair.append([repeat, count])
count = 1
repeat = c
# add last pair
if count >= 3:
weak_pair.append([repeat, count])
# length of 'aaaaaa' divide by 3 returns the time of change
change = 0
one = 0
two = 0
for _, length in weak_pair:
change += length // 3
if length % 3 == 0:
one += 1
elif length % 3 == 1:
two += 1
return change, one, two
def minimum_change(password):
print(password, end=' ')
length = length_requirement(password)
category = category_requirement(password)
repeat, one, two = repeat_requirement(password)
# length: delete or insert
# category: insert or replace
# repeat: delete or replace, or insert
print(length, category, repeat, one, two, end=' * ')
# insert or replace is effective
if length >= 0:
return max(length, category, repeat)
else:
# delete required
delete = - length
repeat -= min(delete, one)
repeat -= min(max(delete - one, 0), two * 2) // 2
repeat -= max(delete - one - 2 * two, 0) // 3
return delete + max(category, repeat)
return minimum_change(s)
|
A password is considered strong if below conditions are all met:
It has at least 6 characters and at most 20 characters.
It must contain at least one lowercase letter, at least one uppercase letter, and at least one digit.
It must NOT contain three repeating characters in a row ("...aaa..." is weak, but "...aa...a..." is strong, assuming other conditions are met).
Write a function strongPasswordChecker(s), that takes a string s as input, and return the MINIMUM change required to make s a strong password. If s is already strong, return 0.
Insertion, deletion or replace of any one character are all considered as one change.
|
class Solution:
def strongPasswordChecker(self, s):
"""
:type s: str
:rtype: int
"""
def length_requirement(password):
length = len(password)
# positive means addition, negative means deletion
if length < 6:
return 6 - length
elif length > 20:
return 20 - length
else:
return 0
def category_requirement(password):
# input
string = set(password)
lowercase = set('qwertyuiopasdfghjklzxcvbnm')
uppercase = set('QWERTYUIOPASDFGHJKLZXCVBNM')
digit = set('1234567890')
condition = [lowercase, uppercase, digit]
# output positive for addition
missing = 0
for s in condition:
if not s & string:
missing += 1
return missing
def repeat_requirement(password):
# store the repeated character and counts its occurrence
count = 1
repeat = None
weak_pair = []
for c in password:
if c == repeat:
# the same character
count += 1
else:
# new character
if count >= 3:
weak_pair.append([repeat, count])
count = 1
repeat = c
# add last pair
if count >= 3:
weak_pair.append([repeat, count])
# length of 'aaaaaa' divide by 3 returns the time of change
change = 0
one = 0
two = 0
for _, length in weak_pair:
change += length // 3
if length % 3 == 0:
one += 1
elif length % 3 == 1:
two += 1
return change, one, two
def minimum_change(password):
print(password, end=' ')
length = length_requirement(password)
category = category_requirement(password)
repeat, one, two = repeat_requirement(password)
# length: delete or insert
# category: insert or replace
# repeat: delete or replace, or insert
print(length, category, repeat, one, two, end=' * ')
# insert or replace is effective
if length >= 0:
return max(length, category, repeat)
else:
# delete required
repeat -= min(-length, one)
repeat -= min(max(-length - one, 0), two * 2) // 2
repeat -= max(-length - one - 2 * two, 0) // 3
return -length + max(category, repeat)
return minimum_change(s)
|
In universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum.
Rick stated that magnetic force between two different balls at positions x and y is |x - y|.
Given the integer array position and the integer m. Return the required force.
Example 1:
Input: position = [1,2,3,4,7], m = 3
Output: 3
Explanation: Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3.
Example 2:
Input: position = [5,4,3,2,1,1000000000], m = 2
Output: 999999999
Explanation: We can use baskets 1 and 1000000000.
Constraints:
n == position.length
2 <= n <= 10^5
1 <= position[i] <= 10^9
All integers in position are distinct.
2 <= m <= position.length
|
class Solution:
def maxDistance(self, position: List[int], m: int) -> int:
position.sort()
max_distance_between = (position[-1] - 1) // (m - 1)
min_distance_between = 1
if self.isDistancePossible(max_distance_between, position, m): return max_distance_between
while max_distance_between > min_distance_between + 1:
middle_distance = (min_distance_between + max_distance_between) // 2
if self.isDistancePossible(middle_distance, position, m):
min_distance_between = middle_distance
else:
max_distance_between = middle_distance
return min_distance_between
def isDistancePossible(self, distance, position, m):
used_ball_count = 0
previous_used_position = float('-inf')
for pos in position:
if pos - previous_used_position >= distance:
used_ball_count += 1
previous_used_position = pos
return used_ball_count >= m
|
In universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum.
Rick stated that magnetic force between two different balls at positions x and y is |x - y|.
Given the integer array position and the integer m. Return the required force.
Example 1:
Input: position = [1,2,3,4,7], m = 3
Output: 3
Explanation: Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3.
Example 2:
Input: position = [5,4,3,2,1,1000000000], m = 2
Output: 999999999
Explanation: We can use baskets 1 and 1000000000.
Constraints:
n == position.length
2 <= n <= 10^5
1 <= position[i] <= 10^9
All integers in position are distinct.
2 <= m <= position.length
|
class Solution:
def maxDistance(self, p: List[int], m: int) -> int:
def isvalid(f: int):
buckets, pos = 1, p[0]
for x in p:
if f <= x - pos:
buckets += 1
if buckets == m: return True
pos = x
return False
p.sort()
lb, ub = 1, (p[-1] - p[0]) // (m - 1) + 1
while 1 < ub - lb:
f = (lb + ub) // 2
if isvalid(f): lb = f
else: ub = f
return lb
|
In universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum.
Rick stated that magnetic force between two different balls at positions x and y is |x - y|.
Given the integer array position and the integer m. Return the required force.
Example 1:
Input: position = [1,2,3,4,7], m = 3
Output: 3
Explanation: Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3.
Example 2:
Input: position = [5,4,3,2,1,1000000000], m = 2
Output: 999999999
Explanation: We can use baskets 1 and 1000000000.
Constraints:
n == position.length
2 <= n <= 10^5
1 <= position[i] <= 10^9
All integers in position are distinct.
2 <= m <= position.length
|
class Solution:
def maxDistance(self, position: List[int], m: int) -> int:
position.sort()
res = -1
if m == 2:
return position[-1]-position[0]
def count(spacing):
count = 1
prev_pos = position[0]
for pos in position:
if pos-prev_pos>=spacing:
count+=1
prev_pos = pos
return count
left,right = 1,math.ceil(position[-1]/(m-1))
while left<=right:
mid = (left+right)//2
if count(mid)>=m:
res = mid
left = mid+1
else:
right = mid-1
return res
|
In universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum.
Rick stated that magnetic force between two different balls at positions x and y is |x - y|.
Given the integer array position and the integer m. Return the required force.
Example 1:
Input: position = [1,2,3,4,7], m = 3
Output: 3
Explanation: Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3.
Example 2:
Input: position = [5,4,3,2,1,1000000000], m = 2
Output: 999999999
Explanation: We can use baskets 1 and 1000000000.
Constraints:
n == position.length
2 <= n <= 10^5
1 <= position[i] <= 10^9
All integers in position are distinct.
2 <= m <= position.length
|
class Solution:
def maxDistance(self, position: List[int], m: int) -> int:
sorted_position = sorted(position)
N = len(position)
lo = 1
hi = sorted_position[N-1] - sorted_position[0]
last_achieved = -1
while lo <= hi:
mid = (lo + hi) // 2
if self._try_target(mid, sorted_position, m):
lo = mid+1
last_achieved = mid
else:
hi = mid-1
return last_achieved
def _try_target(self, target: int, positions: List[int], m:int) -> bool:
slotted = 1
last_slotted = positions[0]
for i in range(1, len(positions)):
if positions[i] - last_slotted >= target:
slotted += 1
last_slotted = positions[i]
return slotted >= m
|
In universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum.
Rick stated that magnetic force between two different balls at positions x and y is |x - y|.
Given the integer array position and the integer m. Return the required force.
Example 1:
Input: position = [1,2,3,4,7], m = 3
Output: 3
Explanation: Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3.
Example 2:
Input: position = [5,4,3,2,1,1000000000], m = 2
Output: 999999999
Explanation: We can use baskets 1 and 1000000000.
Constraints:
n == position.length
2 <= n <= 10^5
1 <= position[i] <= 10^9
All integers in position are distinct.
2 <= m <= position.length
|
class Solution:
def maxDistance(self, position: List[int], m: int) -> int:
n = len(position)
position.sort()
@lru_cache(maxsize=None)
def dfs(i, k, i0):
# put k balls into position[i:] with max min force
# i0 is the position with the largest index between position[0] and position[i-1]
# d0 is the max min force between balls placed between position[0] and position[i-1]
if k > (n-i):
return 0
if k == 1:
return position[n-1]-position[i0]
if k == 0:
return 1e20
d = 0
for j in range(i, n):
d_new = dfs(j+1, k-1, j)
d = max(min(d_new, position[j]-position[i0]), d)
return d
#return dfs(1, m-1, 0)
@lru_cache(None)
def f(i, k):
if k == 0:
return float('inf')
if i == len(position):
return float('-inf')
ret = f(i+1, k)
for x in range(i+1, len(position)):
v = min(position[x] - position[i], f(x, k-1))
ret = max(ret, v)
return ret
#return f(0, m-1)
def count(d):
ans, curr = 1, position[0]
for i in range(1, n):
if position[i] - curr >= d:
ans += 1
curr = position[i]
return ans
l, r = 0, position[-1] - position[0]
while l < r:
mid = r - (r - l) // 2
if count(mid) >= m:
l = mid
else:
r = mid - 1
return l
# position = [1,2,3,4,7], m = 3, n=5
# dfs(0, 3, -1e20, 1e20)
# i=0, k=3, n-i=5
# j=0, d0_new = 1e20,
# dfs(1, 2, 0, 1e20): d_new = ?
# dfs(2, 2, 1, 1e20): d_new = ?
# dfs(3, 2, 2, 1e20): d_new =
# dfs(4, 2, 3, 1e20): k=2 > 5-4=1, d_new = 0
|
In universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum.
Rick stated that magnetic force between two different balls at positions x and y is |x - y|.
Given the integer array position and the integer m. Return the required force.
Example 1:
Input: position = [1,2,3,4,7], m = 3
Output: 3
Explanation: Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3.
Example 2:
Input: position = [5,4,3,2,1,1000000000], m = 2
Output: 999999999
Explanation: We can use baskets 1 and 1000000000.
Constraints:
n == position.length
2 <= n <= 10^5
1 <= position[i] <= 10^9
All integers in position are distinct.
2 <= m <= position.length
|
class Solution:
def maxDistance(self, position: List[int], m: int) -> int:
n = len(position)
position.sort()
res = 0
def count(d):
cur, ans = position[0], 1
for i in range(1, n):
if position[i] - cur >= d:
ans += 1
cur = position[i]
return ans
l, r = 0, position[-1] - position[0]
while l < r:
mid = r - (r - l) // 2
if count(mid) >= m:
l = mid
else:
r = mid - 1
return l
|
In universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum.
Rick stated that magnetic force between two different balls at positions x and y is |x - y|.
Given the integer array position and the integer m. Return the required force.
Example 1:
Input: position = [1,2,3,4,7], m = 3
Output: 3
Explanation: Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3.
Example 2:
Input: position = [5,4,3,2,1,1000000000], m = 2
Output: 999999999
Explanation: We can use baskets 1 and 1000000000.
Constraints:
n == position.length
2 <= n <= 10^5
1 <= position[i] <= 10^9
All integers in position are distinct.
2 <= m <= position.length
|
class Solution:
def maxDistance(self, position: List[int], m: int) -> int:
position.sort()
return self.binaryS(0, position[-1], position, m)
def binaryS(self, left, right, position, m):
while left < right:
mid = (left + right) // 2
val = self.check(position, mid + 1, m)
if val: left = mid + 1
else: right = mid
return right
def check(self, position, interval, m) -> bool:
total = 1
start = position[0]
for i in range(1, len(position)):
if position[i] - start >= interval:
total += 1
start = position[i]
return total >= m
|
In universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum.
Rick stated that magnetic force between two different balls at positions x and y is |x - y|.
Given the integer array position and the integer m. Return the required force.
Example 1:
Input: position = [1,2,3,4,7], m = 3
Output: 3
Explanation: Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3.
Example 2:
Input: position = [5,4,3,2,1,1000000000], m = 2
Output: 999999999
Explanation: We can use baskets 1 and 1000000000.
Constraints:
n == position.length
2 <= n <= 10^5
1 <= position[i] <= 10^9
All integers in position are distinct.
2 <= m <= position.length
|
class Solution:
def maxDistance(self, position: List[int], m: int) -> int:
def isPossible(x):
count = m-1
curr = position[0]
for i in range(1,n):
if position[i]-curr>=x:
count-=1
curr = position[i]
if not count:
return True
return False
n = len(position)
position.sort()
lo = 1
hi = position[-1]-position[0]+1
while hi-lo>1:
mid = lo + (hi-lo)//2
if isPossible(mid):
lo = mid
else:
hi = mid
return lo
|
In universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum.
Rick stated that magnetic force between two different balls at positions x and y is |x - y|.
Given the integer array position and the integer m. Return the required force.
Example 1:
Input: position = [1,2,3,4,7], m = 3
Output: 3
Explanation: Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3.
Example 2:
Input: position = [5,4,3,2,1,1000000000], m = 2
Output: 999999999
Explanation: We can use baskets 1 and 1000000000.
Constraints:
n == position.length
2 <= n <= 10^5
1 <= position[i] <= 10^9
All integers in position are distinct.
2 <= m <= position.length
|
import numpy as np
class Solution:
def maxDistance(self, position: List[int], m: int) -> int:
# Choose m values from n such that the minimum of the differences is maximized
position.sort()
def check(check_val):
temp_m = m-1
previous_pos = position[0]
for p in position[1:]:
if p - previous_pos >= check_val:
previous_pos = p
temp_m -= 1
if temp_m == 0:
return True
return False
l = 0 # min return value
r = (position[-1] - position[0]) # max return value
ret = l
while l <= r:
val = (l+r)//2
if check(val):
ret = max(ret, val)
l = val + 1
else:
r = val-1
return ret
|
In universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum.
Rick stated that magnetic force between two different balls at positions x and y is |x - y|.
Given the integer array position and the integer m. Return the required force.
Example 1:
Input: position = [1,2,3,4,7], m = 3
Output: 3
Explanation: Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3.
Example 2:
Input: position = [5,4,3,2,1,1000000000], m = 2
Output: 999999999
Explanation: We can use baskets 1 and 1000000000.
Constraints:
n == position.length
2 <= n <= 10^5
1 <= position[i] <= 10^9
All integers in position are distinct.
2 <= m <= position.length
|
class Solution:
def maxDistance(self, position: List[int], m: int) -> int:
position.sort()
return self.binaryS(0, position[-1], position, m)
def binaryS(self, left, right, position, m):
while left < right:
mid = (left + right) // 2
val = self.check(position, mid + 1, m)
if val: left = mid + 1
else: right = mid
return left
def check(self, position, interval, m) -> bool:
total = 1
start = position[0]
for i in range(1, len(position)):
if position[i] - start >= interval:
total += 1
start = position[i]
return total >= m
|
In universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum.
Rick stated that magnetic force between two different balls at positions x and y is |x - y|.
Given the integer array position and the integer m. Return the required force.
Example 1:
Input: position = [1,2,3,4,7], m = 3
Output: 3
Explanation: Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3.
Example 2:
Input: position = [5,4,3,2,1,1000000000], m = 2
Output: 999999999
Explanation: We can use baskets 1 and 1000000000.
Constraints:
n == position.length
2 <= n <= 10^5
1 <= position[i] <= 10^9
All integers in position are distinct.
2 <= m <= position.length
|
class Solution:
def maxDistance(self, A: List[int], m: int) -> int:
n = len(A)
A.sort()
def count(d):
ans, curr = 1, A[0]
for i in range(1, n):
if A[i] - curr >= d:
ans += 1
curr = A[i]
return ans
l, r = 0, A[-1] - A[0]
while l < r:
mid = (l+r+1) // 2
if count(mid) >= m:
l = mid
else:
r = mid - 1
return l
|
In universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum.
Rick stated that magnetic force between two different balls at positions x and y is |x - y|.
Given the integer array position and the integer m. Return the required force.
Example 1:
Input: position = [1,2,3,4,7], m = 3
Output: 3
Explanation: Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3.
Example 2:
Input: position = [5,4,3,2,1,1000000000], m = 2
Output: 999999999
Explanation: We can use baskets 1 and 1000000000.
Constraints:
n == position.length
2 <= n <= 10^5
1 <= position[i] <= 10^9
All integers in position are distinct.
2 <= m <= position.length
|
class Solution:
def maxDistance(self, position: List[int], m: int) -> int:
n = len(position)
position.sort()
def count(d):
ans, curr = 1, position[0]
for i in range(1, n):
if position[i] - curr >= d:
ans += 1
curr = position[i]
return ans
l, r = 0, position[-1] - position[0]
while l <= r:
mid = r - (r - l) // 2
if count(mid) >= m:
l = mid + 1
else:
r = mid - 1
return r
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.