inputs
stringlengths 50
14k
| targets
stringlengths 4
655k
|
|---|---|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
n=len(arr)
i=0
for i in range(n-1):
if arr[i+1]<arr[i]:
break
left=i
for i in range(n-1,0,-1):
if arr[i-1]>arr[i]:
break
right=i
if right<=left:
return 0
i=0
j=right
ans=min(n-left-1,right)
while i<=left and j<n:
if arr[i]<=arr[j]:
ans=min(ans,j-i-1)
i+=1
elif arr[j]<arr[i]:
j+=1
return n-1 if ans==n+1 else ans
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
stack = [(len(arr)-1, arr[-1])]
for i in range(len(arr)-2, -1, -1):
if arr[i] <= arr[i+1]:
stack.append([i, arr[i]])
else:
break
min_len = len(arr)-len(stack)
for i in range(len(arr)):
if i == 0 or arr[i] >= arr[i-1]:
while len(stack) > 0 and (stack[-1][1] < arr[i] or stack[-1][0] == i):
stack.pop()
if len(stack) > 0:
min_len = min(min_len, stack[-1][0]-i-1)
else:
min_len = min(min_len, len(arr)-i-1)
else:
break
return min_len
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
l,r = 0,len(arr) - 1
while l < r and arr[l] <= arr[l + 1]:
l += 1
if l == len(arr) - 1:
return 0
while r >= 0 and arr[r] >= arr[r - 1]:
r -= 1
toRemove = min(len(arr) - l - 1,r)
for iL in range(l + 1):
if arr[iL] <= arr[r]:
toRemove = min(toRemove,r - iL - 1)
l += 1
elif r < len(arr) - 1:
r += 1
else:
break
return toRemove
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
#https://leetcode.com/problems/shortest-subarray-to-be-removed-to-make-array-sorted/discuss/830480/C%2B%2B-O(N)-Sliding-window-Explanation-with-Illustrations
#这道题是two pointer类型题目
#大体的逻辑就是左边一个pointer,右边一个pointer
left = 0
right = len(arr) - 1
#left向右走,如果left+1指向的数字大于等于left就一直走
#如果left一路走到了end,那就说明原list就是sorted的,那就直接return
while left + 1 <= len(arr) - 1 and arr[left] <= arr[left+1]:
left += 1
if left == right:
return 0
#right同理向左走,如果right-1小于等于right就继续走
while right - 1 >= 0 and arr[right] >= arr[right - 1]:
right -= 1
#然后先处理两边 就是当0到right-1 或者 left+1到end 其中一个去掉,也就是去掉两边
#在这种情况下 无论怎么移除中间的部分 都没有办法使两边组合起来成为递增
#这种情况就像[6,7,8,9,10,3,5,20,4,1,2,3]
#left指向10,right指向1 -- 因为只能移除一个subarry所以要从 6到20 和 3到3 中选一个
#所以如果是这种case,那就先要计算两个边较小的那个
#right就是0到right -1 index的长度
#len(arr)- 1 - left 就是 end - left 也就是 left + 1到end index的长度
min_sublen = min(right, len(arr)- 1 - left)
#然后就可以开始进行中间情况的运算
#大概就是在这种情况下我们left和right要进行移动,然后找到最短的中间subarray,使得该array去掉后左右两边能成为递增array
#大概的操作就是比较 两个指针lp和rp 从0到left 和 从right到end
#如果lp小于rp了,那就说明去掉lp和rp中间范围就是递增,此时就可以计算下subarr长度,然后进行比较,留下最小的那个。然后lp向右移动一位再继续比较
#知道lp到达了left,或者rp到达了end,就停止 返回最短的subarry长度
lp = 0
rp = right
#如果lp大于rp,那就说明lp太大了,rp向右移动一位
while lp <= left and rp <= len(arr) - 1:
if arr[lp] > arr[rp]:
rp += 1
#如果lp小于rp了,那就说明去掉lp和rp中间范围就是递增,此时就可以计算下subarr长度,然后进行比较,留下最小的那个。然后lp向右移动一位再继续比较
else:
min_sublen = min(min_sublen, rp-lp-1)
lp += 1
return min_sublen
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
l,r = 0, len(arr)-1
while l < r and arr[l+1] >= arr[l]:
l += 1
if l == len(arr)-1:
return 0
while r > 0 and arr[r-1] <= arr[r]:
r -= 1
toRemove = min(len(arr)-1-l,r)
for iL in range(l+1):
if arr[iL] <= arr[r]:
toRemove = min(toRemove, r-iL-1)
elif r < len(arr)-1:
r += 1
else:
break
return toRemove
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
stack = [(len(arr)-1, arr[-1])]
for i in range(len(arr)-2, -1, -1):
if arr[i] <= arr[i+1]:
stack.append([i, arr[i]])
else:
break
min_len = len(arr)-len(stack)
for i in range(len(arr)):
if i == 0 or arr[i] >= arr[i-1]:
while len(stack) > 0 and (stack[-1][1] < arr[i] or stack[-1][0] <= i):
stack.pop()
if len(stack) > 0:
min_len = min(min_len, stack[-1][0]-i-1)
else:
min_len = min(min_len, len(arr)-i-1)
else:
break
return min_len
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
n = len(arr)
i = 1
if len(arr) <= 1:
return 0
while i < n:
if arr[i] < arr[i-1]:
break
i += 1
max_len = i
if max_len == n:
return 0
ini_ind = i - 1
end_ind = 1
while ini_ind >= 0:
if arr[ini_ind] <= arr[-1]:
break
ini_ind -= 1
max_len = max(max_len, ini_ind + end_ind + 1)
while arr[-end_ind-1] <= arr[-end_ind]:
while ini_ind >= 0:
if arr[ini_ind] <= arr[-end_ind-1]:
break
ini_ind -= 1
end_ind += 1
max_len = max(max_len, ini_ind + end_ind + 1)
return n - max_len
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
start, end = 0, 0
for i in range(1, len(arr)):
if arr[i] < arr[i - 1] or (start and arr[i] < arr[start - 1]):
if not start:
start = i
end = i
if start > 0:
if arr[end] >= arr[start - 1]:
end -= 1
curr_opt = end - start + 1
else:
curr_opt = end - start
for i in range(start):
start -= 1
while (end == len(arr) - 1 or arr[end] <= arr[end + 1]) and ((start and arr[end] >= arr[start - 1]) or not start):
end -= 1
curr_opt = min(curr_opt, end - start + 1)
return curr_opt
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
n = len(arr)
l, r = 0, n-1
while 0 < r and arr[r-1] <= arr[r]:
r -= 1
ret = r
while l == 0 or l < n and arr[l-1] <= arr[l]:
while r<=l or r < n and arr[r] < arr[l]:
r += 1
ret = min(ret, r - l - 1)
l += 1
return ret
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
from typing import *
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
n = len(arr)
i, j = 0, n - 1
while i < n - 1 and arr[i] <= arr[i + 1]:
i += 1
if i == n - 1:
return 0
while j > i and arr[j - 1] <= arr[j]:
j -= 1
res = min(n - i - 1, j)
oldi = i
oldj = j
i = 0
while i <= oldi and j < n:
if arr[i] <= arr[j]:
res = min(res, j - i - 1)
i += 1
else:
j += 1
return res
print(Solution().findLengthOfShortestSubarray([1,3,2,4])) # 1
print(Solution().findLengthOfShortestSubarray([1,2,3,10,4,2,3,5])) # 3
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
desc_idx = []
for idx in range(len(arr)):
if idx > 0 and arr[idx] < arr[idx - 1]:
desc_idx.append(idx-1)
if len(desc_idx) == 0:
return 0
ans = len(arr)
start, end = desc_idx[0], desc_idx[-1]
shift_range = [0 , 1]
for shift1 in shift_range:
for shift2 in shift_range:
left = arr[:start+shift1]
right = arr[end+1+shift2:]
left_extend = -1
right_extend = -1
if len(left) == 0:
right_extend = 0
else:
for idx in range(len(right)):
if right[idx] >= left[-1]:
right_extend = idx
break
if right_extend == -1:
right_extend = len(right)
if len(right) == 0:
left_extend = 0
else:
for idx in range(len(left)):
if left[-(idx+1)] <= right[0]:
left_extend = idx
break
if left_extend == -1:
left_extend = len(left)
ans = min(ans, min(left_extend, right_extend) + (end+1+shift2) - (start + shift1))
#extend.append(left_extend)
#extend.append(right_extend)
#print(extend, ans, desc_idx)
#ans += min(extend)
return ans
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
# [1,2,3,10,4,2,3,5]
r = len(arr) - 1
while r >0 and arr[r] >= arr[r-1]:
r -= 1
ret = r # worst case, remove all left
l = 0
for l in range(len(arr)):
if l>0 and arr[l] < arr[l-1]:
break
if l >= r:
r += 1
while r < len(arr) and arr[l] > arr[r] :
r +=1
ret = min(ret, r-l-1)
return ret
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
n = len(arr)
for i in range(n):
if i+1 >= n or arr[i] > arr[i+1]:
l_end = i
break
for i in range(n-1,-1,-1):
if i-1 < 0 or arr[i-1] > arr[i]:
r_start = i
break
if r_start <= l_end: return 0
i, j = 0, r_start
res = min(n-(l_end+1),r_start)
for i in range(l_end+1):
while j < n and arr[i] > arr[j]:
j += 1
res = min(res, j-i-1)
return res
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
'''
[1,2,3,10,4,2,3,5]
3
'''
def doesExist(arr, size, prefix, suffix):
if size >= suffix or (len(arr) -1 - size) <= prefix:
return True
for i in range(len(arr) - size - 1):
if prefix < i:
break
else:
j = i + size + 1
if arr[i] <= arr[j] and j >= suffix:
return True
return False
prefix = 0
suffix = len(arr) - 1
for i in range(1, len(arr)):
if arr[i-1] <= arr[i]:
prefix = i
else:
break
for i in range(len(arr) - 1, 0, -1):
if arr[i-1] <= arr[i]:
suffix = i - 1
else:
break
l = 0
r = len(arr) - 1
optimal = r
while l <= r:
mid = (l + r) // 2
if doesExist(arr, mid, prefix, suffix):
optimal = mid
r = mid - 1
else:
l = mid + 1
return optimal
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
#sliding window
#find the first element which is smaller than the previous one
start_f = 0
while start_f<len(arr)-1:
if arr[start_f+1] >= arr[start_f]:
start_f += 1
else:
break
# if already sorted, end_f is the last element
if start_f == len(arr)-1:
return 0
#find the end point that let end+1 element > start_f element
end_f = len(arr)-1
if arr[-1] < arr[start_f]:
end_f = len(arr)
else:
while end_f-1 >= 0 and arr[end_f-1] >= arr[start_f]:
if arr[end_f-1] <= arr[end_f]: # 逐渐在变小
end_f -= 1
else: #not sorted, 前面一个数比较大了,那么在往前退,会导致第二部分不是sort的
break
#start,end 是需要remove的
start, end = start_f+1, end_f-1
ans = end-start+1
#逐渐把start往前1,看能不能得到更小的值
while start >= 0:
start -= 1
while start ==0 or arr[end] >= arr[start-1]: # start ==0的时候就没有第一部分了
if end == len(arr)-1 or arr[end] <= arr[end+1]: # end最大时,就没有第二部分了
end -= 1
ans = min(ans, end-start+1)
else:
break
return ans
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
import bisect
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
start, end = 0, len(arr)-1
while start < len(arr)-1:
if arr[start] > arr[start+1]:
break
start += 1
if start == len(arr)-1:
return 0
while end > 0:
if arr[end] < arr[end-1]:
break
end -= 1
best_dist = end
for i in range(start, -1, -1):
j = bisect.bisect_left(arr, arr[i], end, len(arr))
dist = j - i - 1
best_dist = min(best_dist, dist)
return best_dist
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution(object):
def findLengthOfShortestSubarray(self, A):
N = len(A)
j = N - 1
while j and A[j] >= A[j - 1]:
j -= 1
# A[j:] is monotone increasing
ans = j
for i in range(j):
if i and A[i] < A[i-1]:
break
# A[..i] is monotone increasing
while j < N and A[i] > A[j]:
j += 1
# j is the smallest such that A[i] <= A[j]
# Remove A[i+1..j-1] which has length j - i - 1
ans = min(ans, j - i - 1)
return ans
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
# find the first inst in left side where arr[i] < arr[i-1]
# next, find the first inst in right side where arr[j] < arr[j-1]
# next, we start i from 0, j at j
# we shrink window if arr[i] <= arr[j]
# we expand window if arr[i] > arr[j]
# we store the size of the window to ans
n = len(arr)
left = 0
while (left + 1 < n and arr[left] <= arr[left + 1]):
left += 1
if left == n - 1: return 0
right = n-1
while (right > left and arr[right - 1] <= arr[right]):
right -= 1;
ans = min(n - left - 1, right)
i, j = 0, right
while i <= left and j < n:
if arr[i] <= arr[j]:
ans = min(ans, j - i - 1)
i += 1
else:
j+=1
return ans
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
def lowerbound(left, right, target):
while left < right:
mid = left + (right - left) // 2
if arr[mid] == target:
right = mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid
return left
N = len(arr)
i = 0
while i + 1 < N and arr[i] <= arr[i + 1]:
i += 1
if i == N - 1:
return 0
j = N - 1
while j - 1 >= 0 and arr[j] >= arr[j - 1]:
j -=1
if j == 0:
return N - 1
result = min(N - (N-j), N - i - 1)
for k in range(i + 1):
l = lowerbound(j, len(arr), arr[k])
result = min(result, l - (k + 1))
return result
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
l = 0
longest_array = 0
while l < len(arr)-1 and arr[l+1] >= arr[l]:
l += 1
longest_array = l+1
r = len(arr)-1
while r > 0 and arr[r] >= arr[r-1]:
r -= 1
longest_array = max(longest_array, len(arr)-r)
#print(f'{l} {r}')
p1 = 0
p2 = r
while p1 <= l and p2 < len(arr):
if arr[p1] <= arr[p2]:
longest_array = max(longest_array, p1 + len(arr)-p2+1)
p1 += 1
else:
p2 += 1
if len(arr)-longest_array < 0:
return 0
return len(arr) - longest_array
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
arr = [0] + arr + [float('inf')]
left = 0
right = len(arr) - 1
while left != right:
if arr[left + 1] < arr[left]:
break
left += 1
while left != right:
if arr[right - 1] > arr[right]:
break
right -= 1
if right == left: return 0
return search(left, right, arr)
def search(leftidx, rightidx, arr):
if arr[rightidx] >= arr[leftidx]: return rightidx - leftidx - 1
leftsearch = rightsearch = midsearch = len(arr)
if leftidx > 0:
leftsearch = search(leftidx - 1, rightidx, arr)
if rightidx < len(arr) - 1:
rightsearch = search(leftidx, rightidx + 1, arr)
if leftidx > 0 and rightidx < len(arr) - 1:
midsearch = search(leftidx - 1, rightidx + 1, arr)
return min(leftsearch, rightsearch, midsearch)
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
n=len(arr)
left,right=-1,-1
for i in range(n-1):
if arr[i]>arr[i+1]:
left=i+1
break
if left==-1:
return 0
for j in range(n-1, 0, -1):
if arr[j]<arr[j-1]:
right=j-1
break
if right==-1:
return 0
ans=min(right+1, n-left)
i=0
for j in range(right+1,n):
while i<left and arr[i]<=arr[j]:
i+=1
ans=min(ans, j-i)
if i==left:
break
return ans
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
n=len(arr)
ndpreflen=1
for i in range(1,n):
if arr[i]<arr[i-1]: break
ndpreflen+=1
ndsufflen=1
for i in range(1,n):
if arr[n-1-i]>arr[n-i]: break
ndsufflen+=1
if ndpreflen+ndsufflen>n: return 0
sufffirstkeep_idx=n-ndsufflen
ans=min(n-ndpreflen,n-ndsufflen)
for preflastkeep_idx in range(ndpreflen):
while sufffirstkeep_idx<n and arr[sufffirstkeep_idx]<arr[preflastkeep_idx]:
sufffirstkeep_idx+=1
if sufffirstkeep_idx==n: break
ans=min(ans,sufffirstkeep_idx-preflastkeep_idx-1)
return ans
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
'''
https://leetcode.com/problems/shortest-subarray-to-be-removed-to-make-array-sorted/discuss/830480/C%2B%2B-O(N)-Sliding-window-Explanation-with-Illustrations
1,2,3,10,4,2,3,5]
1 2 2 3 3 4 5 10
'''
def findLengthOfShortestSubarray(self, A: List[int]) -> int:
N = len(A)
left, right = 0, N - 1
while left + 1 < N and A[left] <= A[left + 1]:
left += 1
if left == N - 1: # not decreasing already
return 0
while right > left and A[right - 1] <= A[right]:
right -= 1
ans = min(N - left - 1, right)
i, j = 0, right
while i <= left and j < N:
if A[j] >= A[i]:
# can remove
ans = min(ans, j - i - 1)
i += 1 # then shrink silde window
else:
# enlarge slide window
j += 1
return ans
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
from bisect import bisect_right
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
arr = [float('-inf')] + arr + [float('inf')]
if arr == sorted(arr): return 0
N = len(arr)
negatives = [None, None]
for i in range(1, N):
diff = arr[i] - arr[i-1]
if diff < 0:
if negatives[0] is None:
negatives[0] = i
negatives[1] = i
ans = float('inf')
for j in range(negatives[1], N):
idx = bisect_right(arr, arr[j], hi=negatives[0])
ans = min(ans, j - idx)
return ans
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
n = len(arr)
if n==0:
return 0
l, r = 0,n-1
while l < n-1 and arr[l] <= arr[l+1]:
l += 1
while r > 0 and arr[r-1] <= arr[r]:
r -= 1
nums_to_rm = min(n - 1 - l, r)
for c in range(l+1):
if arr[c] <= arr[r]:
nums_to_rm = min(nums_to_rm, max(0,r-c-1))
else:
if r < n-1:
r += 1
else:
break
return nums_to_rm
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
if not arr:
return 0
a,temp= [],[]
temp.append(arr[0])
for i in range(1,len(arr)):
if arr[i] - arr[i - 1] >= 0:
temp.append(arr[i])
else:
a.append(temp)
temp = []
temp.append(arr[i])
if temp:
a.append(temp)
if len(a)<=1:
return 0
else:
deletelen=[]
a0,a_1=a[0],a[-1]
deletelen.append(len(arr)-len(a0))
deletelen.append(len(arr)-len(a_1))
if a0[-1]<=a_1[0]:
deletelen.append(len(arr)-len(a0)-len(a_1))
else:
for i in range(len(a_1)):
for j in range(len(a0)-1,-1,-1):
if a_1[i]>=a0[j]:
deletelen.append(len(arr) - len(a0) - len(a_1)+i+(len(a0)-j-1))
break
return min(deletelen)
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
if arr == sorted(arr):
return 0
L = len(arr)
left = [arr[0]]
right = [arr[-1]]
for i in range(1, L):
if arr[i] >= left[-1]:
left += [arr[i]]
else:
break
for i in range(L-2, -1, -1):
if arr[i] <= right[0]:
right.insert(0, arr[i])
else:
break
while len(left)-1 >= L-len(right) and left[-1] == right[0]:
left.pop(-1)
print((left, right, L))
ret = 0
arr_len = 0
for i in range(len(left)):
for j in range(len(right)):
temp = 0
if left[i] <= right[j]:
temp = i+1+len(right)-j
break
# if left[i] in right:
# idx_right = right.index(left[i])
# temp = i+1+len(right)-idx_right
# else:
# idx_right = len(right)-1
# temp = 0
arr_len = max(arr_len, temp)
return L-max(len(left), len(right), arr_len)
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
# O(n)
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
# determine right sorted subarray
r = len(arr) - 1
while r >0 and arr[r] >= arr[r-1]:
r -= 1
# r == 0 means array is sorted
if r == 0:
return 0
# now determine left sorted subarray that can be merged with right
ret = r # set ret to worst case, remove all left
l = 0
for l in range(len(arr)):
# if left subarry is not in order anymore, stop, can't do better
if l>0 and arr[l] < arr[l-1]:
break
# if arr[l] is larger than the left edge of right sorted subarray,
# push the edge to the right
# why this work? Is it OK to push to the right? We won't consider
# arr[i+1] and arr[r].
# It's OK! We don't have to consider arr[i+1] and arr[r].
# if arr[i] is larger than the left edge, arr[next i] is larger too!
# so it won't be the possible answer
while r < len(arr) and arr[l] > arr[r] :
r +=1
ret = min(ret, r-l-1)
return ret
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
from collections import deque
import bisect
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
l, r = deque([]), deque([])
for i, x in enumerate(arr):
if len(l) == 0 or x >= l[-1]:
l.append(x)
else:
break
for i, x in enumerate(arr[::-1]):
if len(r) == 0 or x <= r[0]:
r.appendleft(x)
else:
break
if len(l) == len(arr):
return 0
a, b = len(l), len(r)
ans = b
for i, x in enumerate(l):
idx = bisect.bisect_left(r, x)
ans = max(ans, i + 1 + b - idx)
return len(arr) - ans
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
import bisect
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
start = None
for i in range(0, len(arr)-1):
if arr[i] > arr[i+1]:
start = i
break
if start == None:
return 0
for i in range(len(arr)-1, 0, -1):
if arr[i] < arr[i-1]:
end = i
break
best_dist = end
for i in range(start, -1, -1):
j = bisect.bisect_left(arr, arr[i], end, len(arr))
dist = j - i - 1
best_dist = min(best_dist, dist)
return best_dist
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
# Find the longest monotonically non-decreasing prefix array in [0, i]
n = len(arr)
l = 1
while l < n and arr[l-1] <= arr[l]:
l += 1
l -= 1
if l >= n - 2:
return n - 1 - l
# Find the longest monotonically non-decreasing suffix array in [j, n - 1]
r = n - 2
while r >= 0 and arr[r] <= arr[r+1]:
r -= 1
r += 1
if r <= 1:
return r
# Start off with min of either left or right side removed as the min_to_move
min_to_remove = min(n - 1, n - 1 - (l + 1) + 1, r)
# Try to merge [0..i] from the left into [r..n-1]. If it doesn't work,
# push r forward and try again, until we run out of either room for i to expand
# toward the right or for r to push forward to the right.
i = 0
while i < l + 1:
if arr[i] <= arr[r]:
min_to_remove = min(min_to_remove, r - i - 1)
i += 1
elif r < n - 1:
r += 1
# i += 1 # More intuitive and less subtle to NOT increment i
# Why? Because if after i gets incremented a few times to
# i' such that arr[i'] <= arr[r], then arr[r] must be >=
# all elements in [i..i'-1] because elements in [0..l] are
# non-decreasing. In other words as soon we hit line
# `if arr[i] <= arr[r]:` (after incrementing i a few times
# without successfully finding some arr[r], arr[i] <= arr[r]),
# all those values behind arr[i] can now be included in the merged
# result.
else:
break
return min_to_remove
def findLengthOfShortestSubarray_bruteforce_bsearch(self, arr: List[int]) -> int:
# Returns the smallest index `idx` such that arr[idx] >= val
def bsearch(val, low, high):
while low < high:
mid = (low + high) // 2
if arr[mid] >= val:
high = mid
else:
low = mid + 1
if val > arr[high]:
return high + 1
return high
# Find the longest monotonically non-decreasing prefix array in [0, i]
n = len(arr)
curr_max = float('-inf')
i = 0
while i < n:
if arr[i] < curr_max:
break
curr_max = arr[i]
i += 1
i -= 1
if i >= n - 2:
return n - 1 - i
# Find the longest monotonically non-decreasing suffix array in [j, n - 1]
curr_min = float('inf')
j = n - 1
while j >= 0:
if arr[j] > curr_min:
break
curr_min = arr[j]
j -= 1
j += 1
if j <= 1:
return j
# For each value arr[k], in [0, i], find the `right_idx` into the suffix array in [j, n - 1]
# such that arr[k] >= arr[right_idx]. We want to find the one that results in the longest
# sequence [0..k] + [right_idx..n-1]
min_to_remove = float('inf')
for k in range(i, -1, -1):
right_idx = bsearch(arr[k], j, n - 1)
l = k + 1 + n - right_idx
to_remove = n - l
min_to_remove = min(min_to_remove, to_remove)
# For each value arr[k], in [j, n-1], find the `left_idx` into the prefix array in [0, i]
# such that arr[k] >= arr[left_idx - 1]. We want to find the one that results in the longest
# sequence [0..left_idx-1] + [k..n-1]
for k in range(j, n):
left_idx = bsearch(arr[k], 0, i)
l = left_idx + n - k
to_remove = n - l
min_to_remove = min(min_to_remove, to_remove)
return min_to_remove
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
arr = [-float('inf')] + arr + [float('inf')]
sorted_to = [False for _ in range(len(arr))]
sorted_from = [False for _ in range(len(arr))]
rev_arr = arr[::-1]
last_sorted_to = -1
first_sorted_from = -1
shortest = float('inf')
for idx, val in enumerate(arr):
if idx == 0 or val >= arr[idx - 1]:
sorted_to[idx] = True
last_sorted_to = idx
else:
break
for idx, val in enumerate(rev_arr):
if idx == 0 or val <= rev_arr[idx - 1]:
sorted_from[len(arr) - 1 - idx] = True
first_sorted_from = len(arr) - 1 - idx
else:
break
if arr == sorted(arr):
return 0
for i in range(last_sorted_to + 1):
for j in range(first_sorted_from, len(arr)):
if arr[j] >= arr[i]:
shortest = min(shortest, j - i - 1)
break
shortest = min(shortest, len(arr) - i - 1)
return shortest
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
if arr == sorted(arr):
return 0
l = [arr[0]]
r = [arr[-1]]
for i in range(len(arr)):
if arr[i + 1] >= arr[i]:
l.append(arr[i + 1])
else:
break
for i in range(len(arr) - 1, -1, -1):
if arr[i] >= arr[i - 1]:
r.insert(0, arr[i - 1])
else:
break
res1 = len(arr) - len(r)
res2 = len(arr) - len(l)
j = 0
for i in range(len(l)):
while j < len(r) and l[i] > r[j]:
j += 1
if j == len(r):
j -= 1
p = i
while p < len(l) and l[p] <= r[j]:
p += 1
p -= 1
return min(res1, res2, len(arr) - (p + 1 + len(r) - j))
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
l,r = 0,len(arr) - 1
while l < r and arr[l] <= arr[l + 1]:
l += 1
if l == len(arr) - 1:
return 0
while r >= 0 and arr[r] >= arr[r - 1]:
r -= 1
toRemove = min(len(arr) - l - 1,r)
for iL in range(l + 1):
if arr[iL] <= arr[r]:
toRemove = min(toRemove,r - iL - 1)
elif r < len(arr) - 1:
r += 1
return toRemove
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
def lowerbound(left, right, target):
while left < right:
mid = left + (right - left) // 2
if arr[mid] == target:
right = mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid
return left
N = len(arr)
# find the longest ascending array on the left side
i = 0
while i + 1 < N and arr[i] <= arr[i+1]:
i += 1
if i == N - 1:
# it is already in ascending order
return 0
# find the longest ascending array on the right side
j = N - 1
while j - 1 >= 0 and arr[j] >= arr[j-1]:
j -= 1
if j == 0:
# the entire array is in decending order
return N - 1
# keep ascending array on right side or left side
result = min(N - (N - j), N - i -1)
# find the shortest unordered subarray in the middle
for k in range(i+1):
l = lowerbound(j, len(arr), arr[k])
result = min(result, l - (k + 1))
return result
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
if arr == sorted(arr):
return 0
l = [arr[0]]
r = [arr[-1]]
for i in range(len(arr)):
if arr[i + 1] >= arr[i]:
l.append(arr[i + 1])
else:
break
for i in range(len(arr) - 1, -1, -1):
if arr[i] >= arr[i - 1]:
r.insert(0, arr[i - 1])
else:
break
res1 = len(arr) - len(r)
res2 = len(arr) - len(l)
res3 = len(arr)
if l[-1] <= r[0]:
res3 = len(arr) - len(l) - len(r)
res = min(res1, res2, res3)
j = 0
for i in range(len(l)):
while j < len(r) and l[i] > r[j]:
j += 1
if j == len(r):
j -= 1
p = i
while p < len(l) and l[p] <= r[j]:
p += 1
p -= 1
return min(res, len(arr) - (p + 1 + len(r) - j))
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, A):
# For each i, let's look at the best answer A[..i] + A[j..]
# This requires:
# A[..i] monotone increasing; (1)
# A[j..] monotone increasing; (2)
# A[i] <= A[j] (3)
# For each i, lets say the lowest (ie. best) such j = opt(i).
# It turns out that opt(i) is monotone increasing, so we can use
# two pointers.
N = len(A)
j = N - 1
while j and A[j - 1] <= A[j]:
j -= 1
ans = j
# j is lowest such that A[j..] is monotone increasing
for i in range(j):
if i and A[i-1] > A[i]:
break
while j < N and A[i] > A[j]:
j += 1
# Now, j = opt(i): ie., the lowest j such that
# all 3 conditions (1), (2), (3) above are satisified.
ans = min(ans, j - i - 1)
return ans
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
n = len(arr)
answer = n
curr = arr[0]
start = 1
while start < n:
if arr[start] >= curr:
curr = arr[start]
start += 1
else: break
start -= 1
if start == n-1:
return 0
curr = arr[n-1]
end = n-2
while end >= 0:
if arr[end] <= curr:
curr = arr[end]
end -= 1
else: break
end += 1
answer = min(answer, n-start-1, end)
l, r = 0, end
while r < n and l <= start:
if arr[l] <= arr[r]:
answer = min(answer, r-l-1)
l += 1
else:
r += 1
return answer
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr):
n = len(arr)
left, right = 0, n - 1
while left < n - 1 and arr[left] <= arr[left + 1]:
left += 1
if left == n - 1:
return 0
while right > 0 and arr[right - 1] <= arr[right]:
right -= 1
res = min(n - left - 1, right)
j = right
for i in range(left + 1):
while j <= n - 1 and arr[i] > arr[j]:
j += 1
if j <= n - 1:
res = min(res, j - i - 1)
return res
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, a: List[int]) -> int:
n = len(a)
if all(a[i] >= a[i - 1] for i in range(1, n)):
return 0
d = {x: i + 1 for i, x in enumerate(sorted(set(a)))}
a = [d[x] for x in a]
last = [0] * (len(d) + 1)
prev = -1
for i, x in enumerate(a):
if x < prev: break
last[x] = i + 1
prev = x
for i in range(1, len(d) + 1):
if last[i] == 0:
last[i] = last[i - 1]
ans = last[-1]
prev = 1e100
for i, x in enumerate(a[::-1]):
if prev < x: break
ans = max(ans, i + 1 + last[x])
prev = x
return n - ans
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
N = len(arr)
left_idx = 0
while left_idx < N - 1 and arr[left_idx] <= arr[left_idx+1]:
left_idx += 1
if left_idx == N - 1:
return 0
right_idx = N - 1
while right_idx > 1 and arr[right_idx] >= arr[right_idx - 1]:
right_idx -= 1
r = min(N - 1 - left_idx, right_idx)
i = 0
j = right_idx
while i <= left_idx and j <= N - 1:
if arr[j] >= arr[i]:
r = min(r, j - i - 1)
i += 1
else:
j += 1
return r
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
inc_idx = 0
for i in range(1, len(arr)):
if arr[i] >= arr[i-1]:
inc_idx += 1
else:
break
if inc_idx == len(arr) - 1:
return 0
dec_idx = len(arr) - 1
for i in range(len(arr) - 2, -1, -1):
if arr[i] <= arr[i+1]:
dec_idx -= 1
else:
break
l = self.helper(arr[:inc_idx+1], arr[dec_idx:])
return len(arr) - l
def helper(self, arr1: List[int], arr2: List[int]):
print((arr1, arr2))
i, j = 0, 0
l = 0
while i < len(arr1) and j < len(arr2):
while j < len(arr2) and arr1[i] > arr2[j]:
j += 1
if j == len(arr2):
break
l = max(l, i + 1 + len(arr2) - j)
i += 1
return max(len(arr1), len(arr2), l)
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
# 1040
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
n = len(arr)
left_good = [True,]
right_good = [True,]
for i in range(1, n):
if arr[i] >= arr[i-1]:
left_good.append(True)
else:
break
left_good.extend([False] * (n - len(left_good)))
for i in range(n-2, -1, -1):
if arr[i] <= arr[i+1]:
right_good.append(True)
else:
break
right_good.extend([False] * (n - len(right_good)))
right_good.reverse()
high = n
low = 0
def enough(sz):
if sz == n:
return True
if sz == 0:
return left_good[n-1]
for begin in range(n):
end = begin + sz - 1
if end >= n:
return False
a = begin - 1
b = end + 1
if (a < 0 or left_good[a]) and (b == n or right_good[b]) and ((not 0 <= a < b < n) or (arr[a] <= arr[b])):
#print('found ', begin, sz)
return True
return False
#print(left_good, right_good)
while low <= high:
cur = int((low + high) / 2) # low + (high - low) / 2
#print('trying', cur, enough(cur), low, high)
if enough(cur):
high = cur - 1
else:
low = cur + 1
return low
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
l = 0
r = len(arr)-1
while l < len(arr)-1 and arr[l+1] >= arr[l]:
l +=1
if l == len(arr)-1:
return 0
while r > 0 and arr[r-1] <= arr[r]:
r -=1
res = min(len(arr)-l-1, r)
i, j = 0, r
while i <= l and j < len(arr):
if arr[i] <= arr[j]:
res = min(res, j - i - 1)
i +=1
else:
j +=1
return res
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
# [1,2,3,10,4,2,3,5]
r = len(arr) - 1
while r >0 and arr[r] >= arr[r-1]:
r -= 1
ret = r # worst case, remove all left
l = 0
for l in range(len(arr)):
if l>0 and arr[l] < arr[l-1]:
break
if l == r:
r += 1
while r < len(arr) and arr[l] > arr[r] :
r +=1
ret = min(ret, r-l-1)
return ret
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
l = 0
r = len(arr) - 1
while l < r and arr[l] <= arr[l + 1]:
l += 1
if l == r:
return 0
while r > 0 and arr[r] >= arr[r - 1]:
r -= 1
min_remove = min(len(arr) - l - 1, r)
for i in range(l + 1):
if arr[i] <= arr[r]:
min_remove = min(min_remove, r - i - 1)
elif r < len(arr) - 1:
r += 1
else:
break
return min_remove
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
inc_idx = 0
for i in range(1, len(arr)):
if arr[i] >= arr[i-1]:
inc_idx += 1
else:
break
if inc_idx == len(arr) - 1:
return 0
dec_idx = len(arr) - 1
for i in range(len(arr) - 2, -1, -1):
if arr[i] <= arr[i+1]:
dec_idx -= 1
else:
break
l = self.helper(arr[:inc_idx+1], arr[dec_idx:])
return len(arr) - l
def helper(self, arr1: List[int], arr2: List[int]):
print((arr1, arr2))
i, j = 0, 0
l = 0
while i < len(arr1) and j < len(arr2):
while j < len(arr2) and arr1[i] > arr2[j]:
j += 1
if j == len(arr2):
break
l = max(l, i + 1 + len(arr2) - j)
print((i, j, l))
i += 1
return max(len(arr1), len(arr2), l)
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, a: List[int]) -> int:
n = len(a)
if all(a[i] >= a[i - 1] for i in range(1, n)):
return 0
d = {x: i + 1 for i, x in enumerate(sorted(set(a)))}
a = [d[x] for x in a]
last = [0] * (len(d) + 1)
prev = -1
for i, x in enumerate(a):
if x < prev: break
last[x] = i + 1
prev = x
# print(last)
for i in range(1, len(d) + 1):
if last[i] == 0:
last[i] = last[i - 1]
# print(a)
# print(last)
ans = last[-1]
prev = 1e100
for i, x in enumerate(a[::-1]):
if prev < x: break
print(prev, x, last[x], i)
ans = max(ans, i + 1 + last[x])
prev = x
return n - ans
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
n = len(arr)
p1 = p2 = -1
for i in range(1, n):
if arr[i] < arr[i - 1]:
p2 = i
if p1 == -1:
p1 = i
if p1 == -1:
return 0
def chk(l):
nonlocal p1
nonlocal p2
# print (p1, p2)
if l >= p2:
return True
n = len(arr)
for i in range(n):
if i > p1:
return False
if i + l >= n:
return True
if i + l < p2:
continue
if arr[i - 1] <= arr[i + l]:
return True
return False
# print (chk(8))
# return 0
l = 0
r = n
while l < r:
mid = (l + r) // 2
if chk(mid):
r = mid
else:
l = mid + 1
return l
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
n = len(arr)
l = 0
r = n-1
ans = 0
while l < n-1 and arr[l] <= arr[l+1]:
l+=1
if l == n-1:
return 0
ans = n - l - 1
while r >= l and arr[r] >= arr[r-1]:
r-=1
if r == 0:
return n-1
ans = min(ans,r)
i = 0
j = r
while i <= l and j < n:
if arr[i] <= arr[j]:
ans = min(ans, j-i-1)
i+=1
else:
j+=1
return ans
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
n = len(arr)
i, j = 0, n - 1
while i < n - 1 and arr[i] <= arr[i + 1]:
i += 1
if i == n - 1: return 0 # sorted
while j > 0 and arr[j] >= arr[j - 1]:
j -= 1
if j == 0: return n - 1 # reversely sorted
res = min(n - 1 - i, j) # leaving prefix, or suffix after removing
# to merge prefix and suffix
# binary search also works here but worse time complexity:
# need to search each of prefix in suffix (or the other way)
# checking only end of prefix and head of suffix is not enough
for k in range(i + 1):
if arr[k] <= arr[j]:
res = min(res, j - k - 1)
elif j < n - 1:
j += 1
else:
break
return res
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
first, last = -1, -1
length = len(arr)
prev = float('-inf')
for i in range(length):
if arr[i] < prev:
first = i
break
prev = arr[i]
if first == -1:
return 0
after = float('inf')
for i in range(length - 1, -1, -1):
if arr[i] > after:
last = i
break
after = arr[i]
def helper(size):
for i in range(length - size + 1):
if i <= first and i + size > last:
if i + size == length or i == 0:
return True
if arr[i + size] >= arr[i - 1]:
return True
return False
low, high = 1, length - 1
res = float('inf')
while low <= high:
mid = low + (high - low) // 2
if helper(mid):
res = min(res, mid)
high = mid - 1
else:
low = mid + 1
return res
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
i = 0
pref = 1
while i<len(arr)-1:
if arr[i]<=arr[i+1]:
pref+=1
else:
break
i+=1
j = len(arr)-1
suff = 1
while j>0:
if arr[j]>=arr[j-1]:
suff+=1
else:
break
j-=1
ans = min(len(arr)-pref,len(arr)-suff)
pref = i
suff = j
i = 0
j = suff
while i<=pref and j<len(arr):
if arr[i]<=arr[j]:
ans = min(ans,j-i-1)
i+=1
elif arr[j]<arr[i]:
j+=1
# ans = min(ans,j-i-1)
return max(0,ans)
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
# 1 4 5 2 3 2 1 5 6 7
# can be removed only in 3 types
# last, middle, front
#front - what is the longest sorted array in the suffix
#last - what is the longest sorted array in the prefix
#middle - find the prefix and sufix sorting then see if then can be merged else 0
n = len(arr)
if n==1 or n==0:
return 0
front = 0
a = -1
b = -1
last = 0
middle = 0
c = 1
for i in range(1, n):
if arr[i]>=arr[i-1]:
c += 1
else :
a = i-1
front = c
break
if c == n:
a = n-1
front = c
c = 1
for i in range(n-1,1,-1):
if arr[i-1]<=arr[i]:
c += 1
else :
last = c
b = i
break
if c == n:
b = 0
last = c
print((front, a, last, b))
if b !=-1 and a!= -1 :
for i in range(b,n):
if arr[a] <= arr[i]:
middle = max(middle, front+(n-i))
print((1,a,i))
for i in range(0,a+1):
if arr[i] <= arr[b]:
middle = max(middle, last+i+1)
print((2,i, b))
return n-max(last,max(front,middle))
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
from typing import List
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
# 1. formulate two non-decreasing arr
pre_len = 1
while pre_len < len(arr):
if arr[pre_len] < arr[pre_len - 1]:
break
pre_len += 1
arr_a = arr[:pre_len]
if len(arr_a) == len(arr):
return 0
arr_b = [arr[-1]]
for j in range(len(arr) - 2, -1, -1):
if arr[j] <= arr[j + 1]:
arr_b.insert(0, arr[j])
else:
break
# print(arr_a, arr_b)
# 2. Loop through arr_a to find the ans
ans = len(arr) - 1
for i in range(len(arr_a)):
j = self.binary_search(arr_b, arr_a[i])
cut_length = len(arr) - (i + 1) - (len(arr_b) - j)
ans = min(ans, cut_length)
ans = min(ans, len(arr) - len(arr_a))
ans = min(ans, len(arr) - len(arr_b))
return ans
# need to return the index i such that arr[i] >= num
def binary_search(self, arr, num):
low = 0
high = len(arr) - 1
ans = len(arr)
while low <= high:
mid = (low + high) // 2
if arr[mid] >= num:
ans = min(ans, mid)
high = mid - 1
else:
low = mid + 1
return ans
# leetcode submit region end(Prohibit modification and deletion)
def __starting_point():
solution = Solution()
assert (solution.findLengthOfShortestSubarray([1, 2, 3, 10, 4, 2, 3, 5]) == 3)
assert (solution.findLengthOfShortestSubarray([5, 4, 3, 2, 1]) == 4)
assert (solution.findLengthOfShortestSubarray([1, 2, 3]) == 0)
assert (solution.findLengthOfShortestSubarray([13, 0, 14, 7, 18, 18, 18, 16, 8, 15, 20]) == 8)
assert (solution.findLengthOfShortestSubarray([16, 10, 0, 3, 22, 1, 14, 7, 1, 12, 15]) == 8)
__starting_point()
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
A=arr
N = len(A)
j = N-1
while j >= 1 and A[j-1] <= A[j]:
j -= 1
res = j
for i in range(N):
if i >= j or (i > 0 and A[i] < A[i-1]):
break
while j < N and A[i] > A[j]:
j += 1
res = min(res, j-i-1)
return res
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
# [1,2,3,10,4,2,3,5]
r = len(arr) - 1
while r >0 and arr[r] >= arr[r-1]:
r -= 1
ret = r # worst case, remove all left
l = 0
for l in range(len(arr)):
if l>0 and arr[l] < arr[l-1]:
break
if l >= r:
break
while r < len(arr) and arr[l] > arr[r] :
r +=1
print((l,r))
ret = min(ret, r-l-1)
return ret
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
from sortedcontainers import SortedList
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
last = -float('inf')
sl = SortedList()
for i, n in enumerate(arr):
if n < last: break
sl.add(n)
last = n
ans = len(arr) - len(sl)
last = float('inf')
for i in range(len(arr)-1, 0, -1):
if arr[i] > last: break
last = arr[i]
sl_idx = sl.bisect_right(arr[i])
ans = min(ans, i - sl_idx)
return max(0, ans)
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
n = len(arr)
left_idx, right_idx = 0, n - 1
# edge case
# left side
while left_idx < n - 1 and arr[left_idx] <= arr[left_idx + 1]:
left_idx += 1
# right side
while right_idx > 0 and arr[right_idx - 1] <= arr[right_idx]:
right_idx -= 1
nums_to_rm = min(n - left_idx - 1, right_idx)
# print(nums_to_rm)
# general case
for curr_idx in range(left_idx + 1):
if arr[curr_idx] <= arr[right_idx]:
nums_to_rm = min(nums_to_rm, max(0, right_idx - curr_idx - 1))
# print(nums_to_rm)
else:
# arr[curr_idx] > arr[right_idx]
if right_idx < n - 1:
right_idx += 1
else:
break
# [1,2,3,10,4,2,3,5]
# [5,4,3,2,1]
# [1]
return nums_to_rm
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
pre = [True]
pst = [True]
for i in range(1, len(arr)):
if pre[-1] and arr[i]>=arr[i-1]:
pre.append(True)
else: pre.append(False)
if pst[-1] and arr[len(arr)-i-1]<=arr[len(arr)-i]:
pst.append(True)
else: pst.append(False)
pst = pst[::-1]
# print (pre)
# print (pst)
def isPoss(slen):
for i in range(len(arr)-slen+1):
j = i+slen
if not i:
if pst[j]: return True
elif j>len(arr)-1:
if pre[i-1]: return True
else:
if pre[i-1] and pst[j] and arr[i-1]<=arr[j]:
return True
return False
# print (isPoss(1))
l, r = 0, len(arr)
res = r
while l<=r:
m = l + (r-l)//2
if isPoss(m):
res = min(m, res)
r = m - 1
else:
l = m + 1
return res
|
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.
A subarray is a contiguous subsequence of the array.
Return the length of the shortest subarray to remove.
Example 1:
Input: arr = [1,2,3,10,4,2,3,5]
Output: 3
Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].
Example 2:
Input: arr = [5,4,3,2,1]
Output: 4
Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
Example 3:
Input: arr = [1,2,3]
Output: 0
Explanation: The array is already non-decreasing. We do not need to remove any elements.
Example 4:
Input: arr = [1]
Output: 0
Constraints:
1 <= arr.length <= 10^5
0 <= arr[i] <= 10^9
|
class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
# [start_f, end_f] is the first sorting part
start_f, end_f = 0, 0
while end_f+1 < len(arr):
if arr[end_f+1] >= arr[end_f]:
end_f += 1
else:
break
# the entire array is sorted
if end_f == len(arr)-1:
return 0
start_b, end_b = len(arr)-1, len(arr)-1
# the last part is smaller than first part
if arr[-1] < arr[end_f]:
start_b = len(arr)
else:
while start_b-1 >= 0 and arr[start_b-1] >= arr[end_f]:
if arr[start_b-1] <= arr[start_b]:
start_b -= 1
else:
break
print((start_f, end_f, start_b, end_b))
start, end = end_f+1, start_b-1
ans = end-start+1
while start >= 0:
start -= 1
while start == 0 or arr[end] >= arr[start-1]:
if end == len(arr)-1 or arr[end] <= arr[end+1]:
end -= 1
ans = min(ans, end-start+1)
else:
break
return ans
|
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
|
class Solution:
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def prod(nums):
#function to calculate product
prod = 1
for i in nums:
prod*=i
return prod
def listsplit(ls1,index):
result = []
st = -1
for i in index:
if i == 0:
st = i
else:
result.append(ls1[st+1:i])
st = i
if st<len(ls1)-1:
result.append(ls1[st+1:])
return result
#main starts here
if not nums:
return 0
if len(nums) == 1:
return nums[0]
#find zeros: if zeros are included the result would be zeros only
result=[]
if 0 in nums:
zeros = [i for i in range(len(nums)) if nums[i] ==0]
sublist = listsplit(nums,zeros)
result.append(0)
else:
sublist = [nums]
#find negative numbers. consider even or odd
sublist = [i for i in sublist if i]
for i in sublist:
if prod(i) <0:
#there is negative number in the list
negative = [j for j in range(len(i)) if i[j] < 0]
left,right = negative[0],negative[-1]
if len(i) == 1:
result_t = i[0]
elif left == 0 or right == len(i) -1:
result_t = max(prod(i[left+1:]),prod(i[:right]))
else:
left_p,right_p = prod(i[:left]),prod(i[right+1:])
if left_p <= right_p:
result_t = prod(i[left+1:])
else:
result_t = prod(i[:right])
else:
result_t = prod(i)
result.append(result_t)
return max(result)
|
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
|
class Solution:
def maxProduct(self, nums):
self._prod_cache = {}
m_value = None
if len(nums)==1:
return nums[0]
if len(nums)==0:
return 0
for i in range(len(nums)):
a_value = self.get_max_prod(nums, i, 1)
if m_value is None or a_value>m_value:
m_value = a_value
return m_value
def get_max_prod(self, nums, i, acc_p):
if i<0:
return None
if (i, acc_p) in self._prod_cache:
return self._prod_cache[(i, acc_p)]
val = nums[i]
if i>0:
max_p = max(self.get_max_prod(nums, i-1, acc_p*val),
acc_p*val)
else:
max_p = acc_p*val
self._prod_cache[(i, acc_p)]=max_p
return max_p
|
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
|
class Solution:
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n=len(nums)
if n==0: return 0
if n==1: return nums[0]
ans=nums[0]
l=0
r=n-1
prod=1
i=0
while i<n:
if nums[i]==0:
zero_idx=i
return max(self.maxProduct(nums[(zero_idx+1):]), max(0,self.maxProduct(nums[0:zero_idx])))
else:
prod=prod*nums[i]
i=i+1
if prod>0: return prod
prod_right=prod
max_prod_right=prod
prod_left=prod
max_prod_left=prod
if prod<0:
#print(max_prod_right)
while 0<=r:
prod_right=prod_right//nums[r]
r=r-1
if prod_right>max_prod_right:
if prod_right>0:
max_prod_right=prod_right
break
else:
max_prod_right=prod_right
print(max_prod_left)
while l<n:
prod_left=prod_left//nums[l]
l=l+1
#print(l, prod_left,"----", nums[l], nums[l:])
if prod_left>max_prod_left:
if prod_left>0:
max_prod_left=prod_left
break
else:
max_prod_left=prod_left
#print(max_prod_left, max_prod_right)
return max(max_prod_left, max_prod_right)
|
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
|
class Solution:
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums: return 0
res = premax = premin = nums[0]
curmax = curmin = None
for n in nums[1:]:
curmax, curmin = max(premax*n, premin*n, n), min(premax*n, premin*n, n)
premax, premin = curmax, curmin
res = max(res, curmax)
return res
|
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
|
class Solution:
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
glo_max = nums[0]
imax = glo_max
imin = glo_max
i = 1
while i < len(nums):
if nums[i] < 0:
temp = imax
imax = imin
imin = temp
imax = max(nums[i], nums[i] * imax)
imin = min(nums[i], nums[i] * imin)
glo_max = max(glo_max, imax)
i += 1
return glo_max
|
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
|
class Solution(object):
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# track min_negative_product and max_positive_product
if len(nums) == 0:
return nums
if len(nums) == 1:
return nums[0]
curr_min = curr_max = best_max = nums[0]
for i in range(1,len(nums)):
curr_min,curr_max = min(nums[i],nums[i]*curr_min,nums[i]*curr_max),max(nums[i],nums[i]*curr_min,nums[i]*curr_max)
best_max = max(curr_max,best_max)
return best_max
|
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
|
class Solution:
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dp_max=[0]*len(nums)
dp_min=[0]*len(nums)
res=dp_max[0]=dp_min[0]=nums[0]
for i in range(1,len(nums)):
dp_max[i]=max(nums[i],dp_max[i-1]*nums[i],dp_min[i-1]*nums[i])
dp_min[i]=min(nums[i],dp_max[i-1]*nums[i],dp_min[i-1]*nums[i])
res=max(res,dp_max[i])
return res
|
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
|
class Solution:
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max_val = -float("inf")
product = 1
for num in nums:
product *= num
max_val = max(product, max_val)
if num == 0:
product = 1
product = 1
for num in nums[::-1]:
product *= num
max_val = max(product, max_val)
if num == 0:
product = 1
return max_val
|
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
|
class Solution:
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
res = loc_min = loc_max = nums[0]
for i in nums[1:]:
if i < 0:
loc_min, loc_max = loc_max, loc_min
loc_min = min(i, loc_min * i)
loc_max = max(i, loc_max * i)
res = max(loc_min, loc_max, res)
return res
|
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
|
class Solution:
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1:
return nums[0]
else:
result = big = small = nums[0]
for i in nums[1:]:
big, small = max(i, i*big, i*small), min (i,i*small, i*big)
result = max(result, big)
return result
|
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
|
class Solution:
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
dp = [[nums[0], nums[0]]] * n
ans = nums[0]
for i in range(1, n):
temp = [dp[i-1][0] * nums[i], dp[i-1][1] * nums[i], nums[i]]
dp[i][0], dp[i][1] = max(temp), min(temp)
if dp[i][0] > ans:
ans = dp[i][0]
return ans
|
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
|
class Solution:
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
dp = [[nums[0], nums[0]] for _ in range(n)]
ans = nums[0]
for i in range(1, n):
temp = [dp[i-1][0] * nums[i], dp[i-1][1] * nums[i], nums[i]]
dp[i][0], dp[i][1] = max(temp), min(temp)
if dp[i][0] > ans:
ans = dp[i][0]
return ans
# n = len(nums)
# dp = [[nums[0], nums[0]]] * n 尽量不要使用乘法
# ans = nums[0]
# for i in range(1, n):
# temp = [dp[i-1][0] * nums[i], dp[i-1][1] * nums[i], nums[i]]
# dp[i][0], dp[i][1] = max(temp), min(temp) 这样赋值会改变所有值
# if dp[i][0] > ans:
# ans = dp[i][0]
# return dp[-1][0]
|
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
|
class Solution:
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
f = [[nums[0], nums[0]]]
ans = nums[0]
for i in range(1, len(nums)):
f.append([0, 0])
f[i][0] = min(f[i-1][0]*nums[i], f[i-1][1]*nums[i], nums[i])
f[i][1] = max(f[i-1][0]*nums[i], f[i-1][1]*nums[i], nums[i])
ans = max(ans, f[i][1])
return ans
|
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
|
class Solution:
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
largestproduct = []
smallestproduct = []
n =len(nums)
largestproduct.append(nums[0])
smallestproduct.append(nums[0])
for i in range(n-1):
lp = max(max(largestproduct[i]*nums[i+1],smallestproduct[i]*nums[i+1]),nums[i+1])
sp = min(min(largestproduct[i]*nums[i+1],smallestproduct[i]*nums[i+1]),nums[i+1])
largestproduct.append(lp)
smallestproduct.append(sp)
sol = largestproduct[0]
for i in range(n):
sol = max(sol,largestproduct[i])
return sol
|
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
|
class Solution:
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
maxPos = nums[0]
maxNeg = -nums[0]
p = 1
result = nums[0]
while p < len(nums):
if nums[p] >= 0:
tmp1 = max(nums[p], nums[p] * maxPos)
tmp2 = max(-nums[p], nums[p] * maxNeg)
maxPos = tmp1
maxNeg = tmp2
else:
tmp1 = max(nums[p], -nums[p] * maxNeg)
tmp2 = max(-nums[p], -nums[p] * maxPos)
maxPos = tmp1
maxNeg = tmp2
print((nums[p], maxPos, maxNeg))
result = max(result, maxPos)
p += 1
return result
|
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
|
class Solution:
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
maxP = nums[0]
minP = nums[0]
p = 1
result = nums[0]
while p < len(nums):
tmp1 = max(nums[p], nums[p] * maxP, nums[p] * minP)
tmp2 = min(nums[p], nums[p] * maxP, nums[p] * minP)
maxP = tmp1
minP = tmp2
print((nums[p], maxP, minP))
result = max(result, maxP)
p += 1
return result
|
You are given an integer num. You will apply the following steps exactly two times:
Pick a digit x (0 <= x <= 9).
Pick another digit y (0 <= y <= 9). The digit y can be equal to x.
Replace all the occurrences of x in the decimal representation of num by y.
The new integer cannot have any leading zeros, also the new integer cannot be 0.
Let a and b be the results of applying the operations to num the first and second times, respectively.
Return the max difference between a and b.
Example 1:
Input: num = 555
Output: 888
Explanation: The first time pick x = 5 and y = 9 and store the new integer in a.
The second time pick x = 5 and y = 1 and store the new integer in b.
We have now a = 999 and b = 111 and max difference = 888
Example 2:
Input: num = 9
Output: 8
Explanation: The first time pick x = 9 and y = 9 and store the new integer in a.
The second time pick x = 9 and y = 1 and store the new integer in b.
We have now a = 9 and b = 1 and max difference = 8
Example 3:
Input: num = 123456
Output: 820000
Example 4:
Input: num = 10000
Output: 80000
Example 5:
Input: num = 9288
Output: 8700
Constraints:
1 <= num <= 10^8
|
class Solution:
def maxDiff(self, num: int) -> int:
if num < 10: return 8
a = b = str(num)
i = 0
while i < len(a):
if a[i] == '9':
i += 1
else:
a = a.replace(a[i], '9')
break
if b[0] != '1':
b = b.replace(b[0], '1')
else:
i = 1
while i < len(b):
if b[i] == '1' or b[i] == '0':
i += 1
else:
b = b.replace(b[i], '0')
break
#print(a,b)
return int(a) - int(b)
|
You are given an integer num. You will apply the following steps exactly two times:
Pick a digit x (0 <= x <= 9).
Pick another digit y (0 <= y <= 9). The digit y can be equal to x.
Replace all the occurrences of x in the decimal representation of num by y.
The new integer cannot have any leading zeros, also the new integer cannot be 0.
Let a and b be the results of applying the operations to num the first and second times, respectively.
Return the max difference between a and b.
Example 1:
Input: num = 555
Output: 888
Explanation: The first time pick x = 5 and y = 9 and store the new integer in a.
The second time pick x = 5 and y = 1 and store the new integer in b.
We have now a = 999 and b = 111 and max difference = 888
Example 2:
Input: num = 9
Output: 8
Explanation: The first time pick x = 9 and y = 9 and store the new integer in a.
The second time pick x = 9 and y = 1 and store the new integer in b.
We have now a = 9 and b = 1 and max difference = 8
Example 3:
Input: num = 123456
Output: 820000
Example 4:
Input: num = 10000
Output: 80000
Example 5:
Input: num = 9288
Output: 8700
Constraints:
1 <= num <= 10^8
|
class Solution:
def maxDiff(self, num: int) -> int:
num = [int(c) for c in str(num)]
max_num, min_num = num[:], num[:]
for v in num:
if v < 9:
max_num = [digit if digit != v else 9 for digit in num]
break
if num[0] != 1:
min_num = [digit if digit != num[0] else 1 for digit in num]
else:
for v in num[1:]:
if v > 1:
min_num = [digit if digit != v else 0 for digit in num]
break
print((max_num, min_num))
return int(''.join([str(digit) for digit in max_num]))-int(''.join([str(digit) for digit in min_num]))
|
You are given an integer num. You will apply the following steps exactly two times:
Pick a digit x (0 <= x <= 9).
Pick another digit y (0 <= y <= 9). The digit y can be equal to x.
Replace all the occurrences of x in the decimal representation of num by y.
The new integer cannot have any leading zeros, also the new integer cannot be 0.
Let a and b be the results of applying the operations to num the first and second times, respectively.
Return the max difference between a and b.
Example 1:
Input: num = 555
Output: 888
Explanation: The first time pick x = 5 and y = 9 and store the new integer in a.
The second time pick x = 5 and y = 1 and store the new integer in b.
We have now a = 999 and b = 111 and max difference = 888
Example 2:
Input: num = 9
Output: 8
Explanation: The first time pick x = 9 and y = 9 and store the new integer in a.
The second time pick x = 9 and y = 1 and store the new integer in b.
We have now a = 9 and b = 1 and max difference = 8
Example 3:
Input: num = 123456
Output: 820000
Example 4:
Input: num = 10000
Output: 80000
Example 5:
Input: num = 9288
Output: 8700
Constraints:
1 <= num <= 10^8
|
class Solution:
def maxDiff(self, num: int) -> int:
replaces = []
num = str(num)
for i in range(0, 10):
for j in range(0, 10):
rep_num = num.replace(str(i), str(j))
if rep_num[0] != '0':
replaces.append(int(rep_num))
return max(replaces) - min(replaces)
|
You are given an integer num. You will apply the following steps exactly two times:
Pick a digit x (0 <= x <= 9).
Pick another digit y (0 <= y <= 9). The digit y can be equal to x.
Replace all the occurrences of x in the decimal representation of num by y.
The new integer cannot have any leading zeros, also the new integer cannot be 0.
Let a and b be the results of applying the operations to num the first and second times, respectively.
Return the max difference between a and b.
Example 1:
Input: num = 555
Output: 888
Explanation: The first time pick x = 5 and y = 9 and store the new integer in a.
The second time pick x = 5 and y = 1 and store the new integer in b.
We have now a = 999 and b = 111 and max difference = 888
Example 2:
Input: num = 9
Output: 8
Explanation: The first time pick x = 9 and y = 9 and store the new integer in a.
The second time pick x = 9 and y = 1 and store the new integer in b.
We have now a = 9 and b = 1 and max difference = 8
Example 3:
Input: num = 123456
Output: 820000
Example 4:
Input: num = 10000
Output: 80000
Example 5:
Input: num = 9288
Output: 8700
Constraints:
1 <= num <= 10^8
|
class Solution:
def maxDiff(self, num: int) -> int:
numStr1 = list(str(num))
numStr2 = list(str(num))
numStrLen = len(numStr1)
firstChar = numStr1[0]
for i, char in enumerate(numStr1):
if char != firstChar and char > '0':
for j in range(i, numStrLen):
if numStr1[j] == char:
numStr1[j] = '0'
break
if char == firstChar and char > '1':
for j in range(i, numStrLen):
if numStr1[j] == char:
numStr1[j] = '1'
break
for i, char in enumerate(numStr2):
if char < '9':
for j in range(i, numStrLen):
if numStr2[j] == char:
numStr2[j] = '9'
break
# print(numStr1, numStr2)
return int(''.join(numStr2)) - int(''.join(numStr1))
|
You are given an integer num. You will apply the following steps exactly two times:
Pick a digit x (0 <= x <= 9).
Pick another digit y (0 <= y <= 9). The digit y can be equal to x.
Replace all the occurrences of x in the decimal representation of num by y.
The new integer cannot have any leading zeros, also the new integer cannot be 0.
Let a and b be the results of applying the operations to num the first and second times, respectively.
Return the max difference between a and b.
Example 1:
Input: num = 555
Output: 888
Explanation: The first time pick x = 5 and y = 9 and store the new integer in a.
The second time pick x = 5 and y = 1 and store the new integer in b.
We have now a = 999 and b = 111 and max difference = 888
Example 2:
Input: num = 9
Output: 8
Explanation: The first time pick x = 9 and y = 9 and store the new integer in a.
The second time pick x = 9 and y = 1 and store the new integer in b.
We have now a = 9 and b = 1 and max difference = 8
Example 3:
Input: num = 123456
Output: 820000
Example 4:
Input: num = 10000
Output: 80000
Example 5:
Input: num = 9288
Output: 8700
Constraints:
1 <= num <= 10^8
|
class Solution:
def maxDiff(self, num: int) -> int:
return self.findMax(num) - self.findMin(num)
def findMax(self, num):
s = str(num)
org = None
new_s = ''
for c in s:
if c == '9':
new_s += c
continue
if org is None:
org = c
if c == org:
new_s += '9'
else:
new_s += c
return int(new_s)
def findMin(self, num):
s = str(num)
org = None
rep = None
new_s = ''
for i in range(len(s)):
if s[i] == '0':
new_s += s[i]
continue
if i == 0:
if s[0] == '1':
new_s += s[0]
else:
org = s[0]
rep = '1'
new_s += rep
else:
if org is None and s[i] != '1':
org = s[i]
rep = '0'
new_s += rep
elif s[i] == org:
new_s += rep
else:
new_s += s[i]
return int(new_s)
|
You are given an integer num. You will apply the following steps exactly two times:
Pick a digit x (0 <= x <= 9).
Pick another digit y (0 <= y <= 9). The digit y can be equal to x.
Replace all the occurrences of x in the decimal representation of num by y.
The new integer cannot have any leading zeros, also the new integer cannot be 0.
Let a and b be the results of applying the operations to num the first and second times, respectively.
Return the max difference between a and b.
Example 1:
Input: num = 555
Output: 888
Explanation: The first time pick x = 5 and y = 9 and store the new integer in a.
The second time pick x = 5 and y = 1 and store the new integer in b.
We have now a = 999 and b = 111 and max difference = 888
Example 2:
Input: num = 9
Output: 8
Explanation: The first time pick x = 9 and y = 9 and store the new integer in a.
The second time pick x = 9 and y = 1 and store the new integer in b.
We have now a = 9 and b = 1 and max difference = 8
Example 3:
Input: num = 123456
Output: 820000
Example 4:
Input: num = 10000
Output: 80000
Example 5:
Input: num = 9288
Output: 8700
Constraints:
1 <= num <= 10^8
|
class Solution:
def maxDiff(self, num: int) -> int:
s = str(num)
a = True
i = 0
while i<len(s):
if a and int(s[i])<9:
n = s[i]
a = False
if not a:
if s[i] == n:
s = s[:i]+'9'+s[i+1:]
i+=1
n1 = int(s)
s = str(num)
a = True
if int(s[0])>1:
n = s[0]
y = '1'
s = y+s[1:]
a = False
i = 1
while i<len(s):
if a and int(s[i])>0:
if s[i]!=s[0]:
n = s[i]
y = '0'
a = False
if not a:
if s[i] == n:
s = s[:i]+y+s[i+1:]
i+=1
n2 = int(s)
return n1-n2
|
You are given an integer num. You will apply the following steps exactly two times:
Pick a digit x (0 <= x <= 9).
Pick another digit y (0 <= y <= 9). The digit y can be equal to x.
Replace all the occurrences of x in the decimal representation of num by y.
The new integer cannot have any leading zeros, also the new integer cannot be 0.
Let a and b be the results of applying the operations to num the first and second times, respectively.
Return the max difference between a and b.
Example 1:
Input: num = 555
Output: 888
Explanation: The first time pick x = 5 and y = 9 and store the new integer in a.
The second time pick x = 5 and y = 1 and store the new integer in b.
We have now a = 999 and b = 111 and max difference = 888
Example 2:
Input: num = 9
Output: 8
Explanation: The first time pick x = 9 and y = 9 and store the new integer in a.
The second time pick x = 9 and y = 1 and store the new integer in b.
We have now a = 9 and b = 1 and max difference = 8
Example 3:
Input: num = 123456
Output: 820000
Example 4:
Input: num = 10000
Output: 80000
Example 5:
Input: num = 9288
Output: 8700
Constraints:
1 <= num <= 10^8
|
class Solution:
def maxDiff(self, num: int) -> int:
if num<10:
return 8
numStr=str(num)
a,b=[],[]
for i in range(len(numStr)):
a.append(numStr[i])
b.append(numStr[i])
for i in range(len(a)):
temp=a[i]
if not a[i]=='9':
for j in range(len(a)):
if a[j]==temp:
a[j]='9'
break
for i in range(len(b)):
if i==0:
temp=b[0]
if not b[0]=='1':
for j in range(len(b)):
if b[j]==temp:
b[j]='1'
break
else:
temp=b[i]
if not b[i]=='0' and not b[i]=='1':
for j in range(len(b)):
if b[j]==temp:
b[j]='0'
break
c,d='',''
for i in range(len(numStr)):
c,d=c+a[i],d+b[i]
return int(c)-int(d)
|
You are given an integer num. You will apply the following steps exactly two times:
Pick a digit x (0 <= x <= 9).
Pick another digit y (0 <= y <= 9). The digit y can be equal to x.
Replace all the occurrences of x in the decimal representation of num by y.
The new integer cannot have any leading zeros, also the new integer cannot be 0.
Let a and b be the results of applying the operations to num the first and second times, respectively.
Return the max difference between a and b.
Example 1:
Input: num = 555
Output: 888
Explanation: The first time pick x = 5 and y = 9 and store the new integer in a.
The second time pick x = 5 and y = 1 and store the new integer in b.
We have now a = 999 and b = 111 and max difference = 888
Example 2:
Input: num = 9
Output: 8
Explanation: The first time pick x = 9 and y = 9 and store the new integer in a.
The second time pick x = 9 and y = 1 and store the new integer in b.
We have now a = 9 and b = 1 and max difference = 8
Example 3:
Input: num = 123456
Output: 820000
Example 4:
Input: num = 10000
Output: 80000
Example 5:
Input: num = 9288
Output: 8700
Constraints:
1 <= num <= 10^8
|
class Solution:
def maxDiff(self, num: int) -> int:
maxi = '-inf'
mini = 'inf'
num = str(num)
leading = num[0]
for a in set(num):
a = str(a)
for b in range(10):
if (not b) and (a == leading):
continue
b = str(b)
temp = num.replace(a, b)
mini = min(mini, temp)
maxi = max(maxi, temp)
return int(maxi) - int(mini)
|
You are given an integer num. You will apply the following steps exactly two times:
Pick a digit x (0 <= x <= 9).
Pick another digit y (0 <= y <= 9). The digit y can be equal to x.
Replace all the occurrences of x in the decimal representation of num by y.
The new integer cannot have any leading zeros, also the new integer cannot be 0.
Let a and b be the results of applying the operations to num the first and second times, respectively.
Return the max difference between a and b.
Example 1:
Input: num = 555
Output: 888
Explanation: The first time pick x = 5 and y = 9 and store the new integer in a.
The second time pick x = 5 and y = 1 and store the new integer in b.
We have now a = 999 and b = 111 and max difference = 888
Example 2:
Input: num = 9
Output: 8
Explanation: The first time pick x = 9 and y = 9 and store the new integer in a.
The second time pick x = 9 and y = 1 and store the new integer in b.
We have now a = 9 and b = 1 and max difference = 8
Example 3:
Input: num = 123456
Output: 820000
Example 4:
Input: num = 10000
Output: 80000
Example 5:
Input: num = 9288
Output: 8700
Constraints:
1 <= num <= 10^8
|
class Solution:
def maxDiff(self, num: int) -> int:
a = []
s = str(num)
for i in range(0, 10):
for j in s:
n = s.replace(j, str(i))
m = int(n)
if m != 0 and n[0] != '0':
a.append(m)
diff = max(a) - min(a)
return diff
|
Given an array of integers arr of even length n and an integer k.
We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k.
Return True If you can find a way to do that or False otherwise.
Example 1:
Input: arr = [1,2,3,4,5,10,6,7,8,9], k = 5
Output: true
Explanation: Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10).
Example 2:
Input: arr = [1,2,3,4,5,6], k = 7
Output: true
Explanation: Pairs are (1,6),(2,5) and(3,4).
Example 3:
Input: arr = [1,2,3,4,5,6], k = 10
Output: false
Explanation: You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10.
Example 4:
Input: arr = [-10,10], k = 2
Output: true
Example 5:
Input: arr = [-1,1,-2,2,-3,3,-4,4], k = 3
Output: true
Constraints:
arr.length == n
1 <= n <= 10^5
n is even.
-10^9 <= arr[i] <= 10^9
1 <= k <= 10^5
|
class Solution:
def canArrange(self, arr: List[int], k: int) -> bool:
freq = [0] * k
for n in arr:
freq[n%k] += 1
if freq[0] % 2: return False
for i in range(1, (k//2)+1):
if freq[i] != freq[k-i]: return False
if k%2 is 0:
if freq[k//2]%2: return False
return True
|
Given an array of integers arr of even length n and an integer k.
We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k.
Return True If you can find a way to do that or False otherwise.
Example 1:
Input: arr = [1,2,3,4,5,10,6,7,8,9], k = 5
Output: true
Explanation: Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10).
Example 2:
Input: arr = [1,2,3,4,5,6], k = 7
Output: true
Explanation: Pairs are (1,6),(2,5) and(3,4).
Example 3:
Input: arr = [1,2,3,4,5,6], k = 10
Output: false
Explanation: You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10.
Example 4:
Input: arr = [-10,10], k = 2
Output: true
Example 5:
Input: arr = [-1,1,-2,2,-3,3,-4,4], k = 3
Output: true
Constraints:
arr.length == n
1 <= n <= 10^5
n is even.
-10^9 <= arr[i] <= 10^9
1 <= k <= 10^5
|
class Solution:
def canArrange(self, arr, k):
rem = [0] * k
for a in arr:
rem[a % k] += 1
if rem[0] % 2 != 0:
return False
for i in range(1, (k - 1) // 2 + 1):
if rem[k - i] != rem[i]:
return False
return True
|
Given an array of integers arr of even length n and an integer k.
We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k.
Return True If you can find a way to do that or False otherwise.
Example 1:
Input: arr = [1,2,3,4,5,10,6,7,8,9], k = 5
Output: true
Explanation: Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10).
Example 2:
Input: arr = [1,2,3,4,5,6], k = 7
Output: true
Explanation: Pairs are (1,6),(2,5) and(3,4).
Example 3:
Input: arr = [1,2,3,4,5,6], k = 10
Output: false
Explanation: You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10.
Example 4:
Input: arr = [-10,10], k = 2
Output: true
Example 5:
Input: arr = [-1,1,-2,2,-3,3,-4,4], k = 3
Output: true
Constraints:
arr.length == n
1 <= n <= 10^5
n is even.
-10^9 <= arr[i] <= 10^9
1 <= k <= 10^5
|
class Solution:
def canArrange(self, arr: List[int], k: int) -> bool:
if len(arr)==1:
return False
arr = collections.Counter(([i%k for i in arr]))
if arr[0]%2 ==1:
return False
i = 1
j = k - 1
while i<=j:
if i==j:
if arr[i]%2==1:
return False
if arr[i]!=arr[j]:
return False
i+=1
j-=1
return True
|
Given an array of integers arr of even length n and an integer k.
We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k.
Return True If you can find a way to do that or False otherwise.
Example 1:
Input: arr = [1,2,3,4,5,10,6,7,8,9], k = 5
Output: true
Explanation: Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10).
Example 2:
Input: arr = [1,2,3,4,5,6], k = 7
Output: true
Explanation: Pairs are (1,6),(2,5) and(3,4).
Example 3:
Input: arr = [1,2,3,4,5,6], k = 10
Output: false
Explanation: You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10.
Example 4:
Input: arr = [-10,10], k = 2
Output: true
Example 5:
Input: arr = [-1,1,-2,2,-3,3,-4,4], k = 3
Output: true
Constraints:
arr.length == n
1 <= n <= 10^5
n is even.
-10^9 <= arr[i] <= 10^9
1 <= k <= 10^5
|
class Solution:
def canArrange(self, arr: List[int], k: int) -> bool:
if len(arr) % 2 != 0:
return False
import collections
ans = []
lookup = collections.defaultdict(list)
for i, num in enumerate(arr):
if (num % k) in lookup:
ans.append((arr[lookup[(num % k)].pop(0)], num))
if lookup[num % k] == []:
del lookup[num % k]
continue
if num % k == 0:
lookup[0].append(i)
else:
lookup[(k - (num % k))].append(i)
return len(ans) == len(arr)//2
|
Given an array of integers arr of even length n and an integer k.
We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k.
Return True If you can find a way to do that or False otherwise.
Example 1:
Input: arr = [1,2,3,4,5,10,6,7,8,9], k = 5
Output: true
Explanation: Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10).
Example 2:
Input: arr = [1,2,3,4,5,6], k = 7
Output: true
Explanation: Pairs are (1,6),(2,5) and(3,4).
Example 3:
Input: arr = [1,2,3,4,5,6], k = 10
Output: false
Explanation: You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10.
Example 4:
Input: arr = [-10,10], k = 2
Output: true
Example 5:
Input: arr = [-1,1,-2,2,-3,3,-4,4], k = 3
Output: true
Constraints:
arr.length == n
1 <= n <= 10^5
n is even.
-10^9 <= arr[i] <= 10^9
1 <= k <= 10^5
|
class Solution:
def canArrange(self, A: List[int], k: int) -> bool:
A.sort(key=lambda x: x%k, reverse=True)
i, n = 1, len(A)
while i < len(A) and A[-i] % k == 0:
if A[-i - 1] % k: return False
else:
i += 2
if i < len(A):
j = 0
i0 = i
while A[-i] % k and j < (n - i0 + 1) // 2:
if (A[-i] + A[j]) % k: return False
i += 1
j += 1
return True
|
Given an array of integers arr of even length n and an integer k.
We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k.
Return True If you can find a way to do that or False otherwise.
Example 1:
Input: arr = [1,2,3,4,5,10,6,7,8,9], k = 5
Output: true
Explanation: Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10).
Example 2:
Input: arr = [1,2,3,4,5,6], k = 7
Output: true
Explanation: Pairs are (1,6),(2,5) and(3,4).
Example 3:
Input: arr = [1,2,3,4,5,6], k = 10
Output: false
Explanation: You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10.
Example 4:
Input: arr = [-10,10], k = 2
Output: true
Example 5:
Input: arr = [-1,1,-2,2,-3,3,-4,4], k = 3
Output: true
Constraints:
arr.length == n
1 <= n <= 10^5
n is even.
-10^9 <= arr[i] <= 10^9
1 <= k <= 10^5
|
class Solution:
def canArrange(self, arr: List[int], k: int) -> bool:
recDict = {}
for i in range(0, k):
recDict[i] = 0
for i in arr:
recDict[i%k] += 1
for i in range(1, k):
if recDict[i] !=recDict[k-i]:
return False
if recDict[0]%2 !=0:
return False
return True
|
Given an array of integers arr of even length n and an integer k.
We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k.
Return True If you can find a way to do that or False otherwise.
Example 1:
Input: arr = [1,2,3,4,5,10,6,7,8,9], k = 5
Output: true
Explanation: Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10).
Example 2:
Input: arr = [1,2,3,4,5,6], k = 7
Output: true
Explanation: Pairs are (1,6),(2,5) and(3,4).
Example 3:
Input: arr = [1,2,3,4,5,6], k = 10
Output: false
Explanation: You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10.
Example 4:
Input: arr = [-10,10], k = 2
Output: true
Example 5:
Input: arr = [-1,1,-2,2,-3,3,-4,4], k = 3
Output: true
Constraints:
arr.length == n
1 <= n <= 10^5
n is even.
-10^9 <= arr[i] <= 10^9
1 <= k <= 10^5
|
from collections import Counter
class Solution:
def canArrange(self, arr: List[int], k: int) -> bool:
li=collections.Counter([x%k for x in arr])
print(li)
for i in li:
if i==0 or li[i]==0:
continue
# print(i,li[i])
if li[k-i]!=li[i] :
return False
if li[0]%2==0:
return True
else:
return False
|
Given an array of integers arr of even length n and an integer k.
We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k.
Return True If you can find a way to do that or False otherwise.
Example 1:
Input: arr = [1,2,3,4,5,10,6,7,8,9], k = 5
Output: true
Explanation: Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10).
Example 2:
Input: arr = [1,2,3,4,5,6], k = 7
Output: true
Explanation: Pairs are (1,6),(2,5) and(3,4).
Example 3:
Input: arr = [1,2,3,4,5,6], k = 10
Output: false
Explanation: You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10.
Example 4:
Input: arr = [-10,10], k = 2
Output: true
Example 5:
Input: arr = [-1,1,-2,2,-3,3,-4,4], k = 3
Output: true
Constraints:
arr.length == n
1 <= n <= 10^5
n is even.
-10^9 <= arr[i] <= 10^9
1 <= k <= 10^5
|
class Solution:
def canArrange(self, arr: List[int], k: int) -> bool:
'''
## APPROACH : 2 SUM ##
## LOGIC ##
\t\t## 1. Store the remainders in the hashmap and check if the current number has remaining remainder available in the hashset ##
freq {remainder: remainder count}
return true if not any of the pairs are true => we check if the freq[k-x%k]!=freq[x%k]. If we find any of such instance to be true, we return false
'''
freq = collections.Counter(map(lambda x: x%k, arr))
return not any(val%2 if not key else val!=freq[k-key] for key,val in freq.items())
|
Given an array of integers arr of even length n and an integer k.
We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k.
Return True If you can find a way to do that or False otherwise.
Example 1:
Input: arr = [1,2,3,4,5,10,6,7,8,9], k = 5
Output: true
Explanation: Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10).
Example 2:
Input: arr = [1,2,3,4,5,6], k = 7
Output: true
Explanation: Pairs are (1,6),(2,5) and(3,4).
Example 3:
Input: arr = [1,2,3,4,5,6], k = 10
Output: false
Explanation: You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10.
Example 4:
Input: arr = [-10,10], k = 2
Output: true
Example 5:
Input: arr = [-1,1,-2,2,-3,3,-4,4], k = 3
Output: true
Constraints:
arr.length == n
1 <= n <= 10^5
n is even.
-10^9 <= arr[i] <= 10^9
1 <= k <= 10^5
|
class Solution:
def canArrange(self, arr: List[int], k: int) -> bool:
cnt = [0] * k
for a in arr:
a %= k
remainder = (k - a) % k
if cnt[remainder] > 0:
cnt[remainder] -= 1
else:
cnt[a] += 1
return all(c == 0 for c in cnt)
|
Given an array of integers arr of even length n and an integer k.
We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k.
Return True If you can find a way to do that or False otherwise.
Example 1:
Input: arr = [1,2,3,4,5,10,6,7,8,9], k = 5
Output: true
Explanation: Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10).
Example 2:
Input: arr = [1,2,3,4,5,6], k = 7
Output: true
Explanation: Pairs are (1,6),(2,5) and(3,4).
Example 3:
Input: arr = [1,2,3,4,5,6], k = 10
Output: false
Explanation: You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10.
Example 4:
Input: arr = [-10,10], k = 2
Output: true
Example 5:
Input: arr = [-1,1,-2,2,-3,3,-4,4], k = 3
Output: true
Constraints:
arr.length == n
1 <= n <= 10^5
n is even.
-10^9 <= arr[i] <= 10^9
1 <= k <= 10^5
|
class Solution:
def canArrange(self, arr: List[int], k: int) -> bool:
m = {i:0 for i in range(k)}
for a in arr:
m[a%k] += 1
for i in range(k):
if i == 0:
if m[i] % 2 != 0:
return False
elif m[i] != m[k-i]:
return False
return True
|
Given an array of integers arr of even length n and an integer k.
We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k.
Return True If you can find a way to do that or False otherwise.
Example 1:
Input: arr = [1,2,3,4,5,10,6,7,8,9], k = 5
Output: true
Explanation: Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10).
Example 2:
Input: arr = [1,2,3,4,5,6], k = 7
Output: true
Explanation: Pairs are (1,6),(2,5) and(3,4).
Example 3:
Input: arr = [1,2,3,4,5,6], k = 10
Output: false
Explanation: You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10.
Example 4:
Input: arr = [-10,10], k = 2
Output: true
Example 5:
Input: arr = [-1,1,-2,2,-3,3,-4,4], k = 3
Output: true
Constraints:
arr.length == n
1 <= n <= 10^5
n is even.
-10^9 <= arr[i] <= 10^9
1 <= k <= 10^5
|
class Solution:
def canArrange(self, arr: List[int], k: int) -> bool:
d=collections.Counter()
for e in arr:
t=e%k
d[t]+=1
key = d.keys()
print(d)
for e in key:
if e==0:
continue
if d[e]!=d[k-e]:
return False
else:
if e==k//2 and k%2==0 and d[e]%2!=0:
return False
return True
|
Given an array of integers arr of even length n and an integer k.
We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k.
Return True If you can find a way to do that or False otherwise.
Example 1:
Input: arr = [1,2,3,4,5,10,6,7,8,9], k = 5
Output: true
Explanation: Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10).
Example 2:
Input: arr = [1,2,3,4,5,6], k = 7
Output: true
Explanation: Pairs are (1,6),(2,5) and(3,4).
Example 3:
Input: arr = [1,2,3,4,5,6], k = 10
Output: false
Explanation: You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10.
Example 4:
Input: arr = [-10,10], k = 2
Output: true
Example 5:
Input: arr = [-1,1,-2,2,-3,3,-4,4], k = 3
Output: true
Constraints:
arr.length == n
1 <= n <= 10^5
n is even.
-10^9 <= arr[i] <= 10^9
1 <= k <= 10^5
|
'''
现在需要把数组恰好分成 n / 2 对,以使每对数字的和都能够被 k 整除。
如果存在这样的分法,请返回 True ;否则,返回 False 。
思路:首先和得整除。要凑对,那就是mod能凑对,统计mod能否凑对即可
'''
class Solution:
def canArrange(self, arr: List[int], k: int) -> bool:
mod_count = [0 for i in range(k)]
for i in arr:
mod_count[i % k] += 1
if mod_count[0] % 2:
return False
for i in range(1, len(mod_count)):
if mod_count[i] != mod_count[k-i]:
return False
return True
|
Given an array of integers arr of even length n and an integer k.
We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k.
Return True If you can find a way to do that or False otherwise.
Example 1:
Input: arr = [1,2,3,4,5,10,6,7,8,9], k = 5
Output: true
Explanation: Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10).
Example 2:
Input: arr = [1,2,3,4,5,6], k = 7
Output: true
Explanation: Pairs are (1,6),(2,5) and(3,4).
Example 3:
Input: arr = [1,2,3,4,5,6], k = 10
Output: false
Explanation: You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10.
Example 4:
Input: arr = [-10,10], k = 2
Output: true
Example 5:
Input: arr = [-1,1,-2,2,-3,3,-4,4], k = 3
Output: true
Constraints:
arr.length == n
1 <= n <= 10^5
n is even.
-10^9 <= arr[i] <= 10^9
1 <= k <= 10^5
|
# # O(nlogn) S(n)
# class Solution:
# def canArrange(self, arr: List[int], k: int) -> bool:
# A = [a % k for a in arr]
# A.sort()
# l = 0
# r = len(A) - 1
# while l < len(A) and A[l] == 0:
# l += 1
# if l % 2 == 1:
# return False
# while l < r:
# if A[l] + A[r] != k:
# return False
# l += 1
# r -= 1
# return True
# O(n) S(n)
class Solution:
def canArrange(self, arr: List[int], k: int) -> bool:
c = collections.Counter([i%k for i in arr])
for j in c:
if j == 0:
if c[j]%2!=0: return False
else:
if c[j]!=c[k-j]:return False
return True
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.