inputs
stringlengths 50
14k
| targets
stringlengths 4
655k
|
|---|---|
Given an array of integers arr. Return the number of sub-arrays with odd sum.
As the answer may grow large, the answer must be computed modulo 10^9 + 7.
Example 1:
Input: arr = [1,3,5]
Output: 4
Explanation: All sub-arrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]]
All sub-arrays sum are [1,4,9,3,8,5].
Odd sums are [1,9,3,5] so the answer is 4.
Example 2:
Input: arr = [2,4,6]
Output: 0
Explanation: All sub-arrays are [[2],[2,4],[2,4,6],[4],[4,6],[6]]
All sub-arrays sum are [2,6,12,4,10,6].
All sub-arrays have even sum and the answer is 0.
Example 3:
Input: arr = [1,2,3,4,5,6,7]
Output: 16
Example 4:
Input: arr = [100,100,99,99]
Output: 4
Example 5:
Input: arr = [7]
Output: 1
Constraints:
1 <= arr.length <= 10^5
1 <= arr[i] <= 100
|
class Solution:
def numOfSubarrays(self, arr: List[int]) -> int:
odd = 0
even = 0
n = len(arr)
sumlist = [0]*n
output = 0
for i in range(n-1, -1, -1):
if i != n-1:
sumlist[i] += arr[i] + sumlist[i + 1]
else:
sumlist[i] += arr[i]
if sumlist[i] % 2 == 0:
output += odd
even += 1
else:
output += 1
output += even
odd += 1
output %= (10**9 + 7)
return output
|
Given an array of integers arr. Return the number of sub-arrays with odd sum.
As the answer may grow large, the answer must be computed modulo 10^9 + 7.
Example 1:
Input: arr = [1,3,5]
Output: 4
Explanation: All sub-arrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]]
All sub-arrays sum are [1,4,9,3,8,5].
Odd sums are [1,9,3,5] so the answer is 4.
Example 2:
Input: arr = [2,4,6]
Output: 0
Explanation: All sub-arrays are [[2],[2,4],[2,4,6],[4],[4,6],[6]]
All sub-arrays sum are [2,6,12,4,10,6].
All sub-arrays have even sum and the answer is 0.
Example 3:
Input: arr = [1,2,3,4,5,6,7]
Output: 16
Example 4:
Input: arr = [100,100,99,99]
Output: 4
Example 5:
Input: arr = [7]
Output: 1
Constraints:
1 <= arr.length <= 10^5
1 <= arr[i] <= 100
|
class Solution:
def numOfSubarrays(self, arr: List[int]) -> int:
ans = 0
even = 0
odd = 0
for v in arr:
if v % 2 == 0:
even, odd = even + 1, odd
else:
even, odd = odd, even + 1
ans += odd
return ans % 1000000007
|
Given an array of integers arr. Return the number of sub-arrays with odd sum.
As the answer may grow large, the answer must be computed modulo 10^9 + 7.
Example 1:
Input: arr = [1,3,5]
Output: 4
Explanation: All sub-arrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]]
All sub-arrays sum are [1,4,9,3,8,5].
Odd sums are [1,9,3,5] so the answer is 4.
Example 2:
Input: arr = [2,4,6]
Output: 0
Explanation: All sub-arrays are [[2],[2,4],[2,4,6],[4],[4,6],[6]]
All sub-arrays sum are [2,6,12,4,10,6].
All sub-arrays have even sum and the answer is 0.
Example 3:
Input: arr = [1,2,3,4,5,6,7]
Output: 16
Example 4:
Input: arr = [100,100,99,99]
Output: 4
Example 5:
Input: arr = [7]
Output: 1
Constraints:
1 <= arr.length <= 10^5
1 <= arr[i] <= 100
|
class Solution:
def numOfSubarrays(self, arr: List[int]) -> int:
odd, even = 0,0
arr = [i % 2 for i in arr]
if arr[0] != 0:
odd += 1
else:
even += 1
for i in range(1,len(arr)):
arr[i] = arr[i - 1] + arr[i]
if arr[i] % 2 == 0:
even += 1
else:
odd += 1
ans = 0
for i in arr[::-1]:
if i % 2 == 0 and odd > 0:
ans += odd
even -= 1
elif i % 2 == 1:
ans += (even+1)
odd -= 1
else:
continue
return ans % (10**9 + 7)
|
Given an array of integers arr. Return the number of sub-arrays with odd sum.
As the answer may grow large, the answer must be computed modulo 10^9 + 7.
Example 1:
Input: arr = [1,3,5]
Output: 4
Explanation: All sub-arrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]]
All sub-arrays sum are [1,4,9,3,8,5].
Odd sums are [1,9,3,5] so the answer is 4.
Example 2:
Input: arr = [2,4,6]
Output: 0
Explanation: All sub-arrays are [[2],[2,4],[2,4,6],[4],[4,6],[6]]
All sub-arrays sum are [2,6,12,4,10,6].
All sub-arrays have even sum and the answer is 0.
Example 3:
Input: arr = [1,2,3,4,5,6,7]
Output: 16
Example 4:
Input: arr = [100,100,99,99]
Output: 4
Example 5:
Input: arr = [7]
Output: 1
Constraints:
1 <= arr.length <= 10^5
1 <= arr[i] <= 100
|
class Solution:
def numOfSubarrays(self, arr: List[int]) -> int:
odd, even = 0,0
arr = [i % 2 for i in arr]
if arr[0] != 0:
odd += 1
else:
even += 1
for i in range(1,len(arr)):
arr[i] = arr[i - 1] + arr[i]
if arr[i] % 2 == 0:
even += 1
else:
odd += 1
ans = 0
for i in arr[::-1]:
if i % 2 == 0 and odd > 0:
ans += odd
even -= 1
elif i % 2 == 1:
ans += (even+1)
odd -= 1
else:
break
return ans % (10**9 + 7)
|
Given an array of integers arr. Return the number of sub-arrays with odd sum.
As the answer may grow large, the answer must be computed modulo 10^9 + 7.
Example 1:
Input: arr = [1,3,5]
Output: 4
Explanation: All sub-arrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]]
All sub-arrays sum are [1,4,9,3,8,5].
Odd sums are [1,9,3,5] so the answer is 4.
Example 2:
Input: arr = [2,4,6]
Output: 0
Explanation: All sub-arrays are [[2],[2,4],[2,4,6],[4],[4,6],[6]]
All sub-arrays sum are [2,6,12,4,10,6].
All sub-arrays have even sum and the answer is 0.
Example 3:
Input: arr = [1,2,3,4,5,6,7]
Output: 16
Example 4:
Input: arr = [100,100,99,99]
Output: 4
Example 5:
Input: arr = [7]
Output: 1
Constraints:
1 <= arr.length <= 10^5
1 <= arr[i] <= 100
|
class Solution:
def numOfSubarrays(self, arr: List[int]) -> int:
dp = [[0, 0]]
ans = 0
for i in arr:
if i % 2 == 0:
dp.append([dp[-1][0] + 1, dp[-1][1]])
else:
dp.append([dp[-1][1], dp[-1][0] + 1])
ans += dp[-1][1]
return int(ans % (1e9 + 7))
|
Given an array of integers arr. Return the number of sub-arrays with odd sum.
As the answer may grow large, the answer must be computed modulo 10^9 + 7.
Example 1:
Input: arr = [1,3,5]
Output: 4
Explanation: All sub-arrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]]
All sub-arrays sum are [1,4,9,3,8,5].
Odd sums are [1,9,3,5] so the answer is 4.
Example 2:
Input: arr = [2,4,6]
Output: 0
Explanation: All sub-arrays are [[2],[2,4],[2,4,6],[4],[4,6],[6]]
All sub-arrays sum are [2,6,12,4,10,6].
All sub-arrays have even sum and the answer is 0.
Example 3:
Input: arr = [1,2,3,4,5,6,7]
Output: 16
Example 4:
Input: arr = [100,100,99,99]
Output: 4
Example 5:
Input: arr = [7]
Output: 1
Constraints:
1 <= arr.length <= 10^5
1 <= arr[i] <= 100
|
class Solution:
def numOfSubarrays(self, arr: List[int]) -> int:
dp=[-1 for i in range(len(arr))]
dp[0]=[(arr[0]+1)%2,arr[0]%2]
total=dp[0][1]
for k in range(1,len(arr)):
if arr[k]%2==0:
dp[k]=[(dp[k-1][0]+1)%(10**9+7),(dp[k-1][1])%(10**9+7)]
total+=dp[k][1]
total=total%(10**9+7)
else:
dp[k]=[(dp[k-1][1])%(10**9+7),(dp[k-1][0]+1)%(10**9+7)]
total+=dp[k][1]
total=total%(10**9+7)
return total%(10**9+7)
|
Given an array of integers arr. Return the number of sub-arrays with odd sum.
As the answer may grow large, the answer must be computed modulo 10^9 + 7.
Example 1:
Input: arr = [1,3,5]
Output: 4
Explanation: All sub-arrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]]
All sub-arrays sum are [1,4,9,3,8,5].
Odd sums are [1,9,3,5] so the answer is 4.
Example 2:
Input: arr = [2,4,6]
Output: 0
Explanation: All sub-arrays are [[2],[2,4],[2,4,6],[4],[4,6],[6]]
All sub-arrays sum are [2,6,12,4,10,6].
All sub-arrays have even sum and the answer is 0.
Example 3:
Input: arr = [1,2,3,4,5,6,7]
Output: 16
Example 4:
Input: arr = [100,100,99,99]
Output: 4
Example 5:
Input: arr = [7]
Output: 1
Constraints:
1 <= arr.length <= 10^5
1 <= arr[i] <= 100
|
class Solution:
def numOfSubarrays(self, arr: List[int]) -> int:
mod = 10**9 + 7
result = 0
sumOdd = [0] * (len(arr))
sumEven = [0] * (len(arr))
if arr[0] % 2 == 1:
sumOdd[0] = 1
sumEven[0] = 0
else:
sumOdd[0] = 0
sumEven[0] = 1
for i in range(1,len(sumOdd)):
if arr[i] % 2 == 0:
sumOdd[i] = sumOdd[i - 1]
sumEven[i] = sumEven[i - 1] + 1
else:
sumOdd[i] = sumEven[i - 1] + 1
sumEven[i] = sumOdd[i - 1]
return sum(sumOdd) % mod
|
Given an array of integers arr. Return the number of sub-arrays with odd sum.
As the answer may grow large, the answer must be computed modulo 10^9 + 7.
Example 1:
Input: arr = [1,3,5]
Output: 4
Explanation: All sub-arrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]]
All sub-arrays sum are [1,4,9,3,8,5].
Odd sums are [1,9,3,5] so the answer is 4.
Example 2:
Input: arr = [2,4,6]
Output: 0
Explanation: All sub-arrays are [[2],[2,4],[2,4,6],[4],[4,6],[6]]
All sub-arrays sum are [2,6,12,4,10,6].
All sub-arrays have even sum and the answer is 0.
Example 3:
Input: arr = [1,2,3,4,5,6,7]
Output: 16
Example 4:
Input: arr = [100,100,99,99]
Output: 4
Example 5:
Input: arr = [7]
Output: 1
Constraints:
1 <= arr.length <= 10^5
1 <= arr[i] <= 100
|
class Solution:
def numOfSubarrays(self, arr: List[int]) -> int:
n = len(arr)
dp = [[0]*2 for _ in range(n+1)]
kMod = 1e9+7
for i, num in enumerate(arr):
if num&1:
#even
dp[i+1][0] = dp[i][1]
#odd
dp[i+1][1] = dp[i][0]+1
else:
#even
dp[i+1][0] = dp[i][0] + 1
#odd
dp[i+1][1] = dp[i][1]
return int(sum([dp[i][1] for i in range(n+1)])%kMod)
|
Given an array of integers arr. Return the number of sub-arrays with odd sum.
As the answer may grow large, the answer must be computed modulo 10^9 + 7.
Example 1:
Input: arr = [1,3,5]
Output: 4
Explanation: All sub-arrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]]
All sub-arrays sum are [1,4,9,3,8,5].
Odd sums are [1,9,3,5] so the answer is 4.
Example 2:
Input: arr = [2,4,6]
Output: 0
Explanation: All sub-arrays are [[2],[2,4],[2,4,6],[4],[4,6],[6]]
All sub-arrays sum are [2,6,12,4,10,6].
All sub-arrays have even sum and the answer is 0.
Example 3:
Input: arr = [1,2,3,4,5,6,7]
Output: 16
Example 4:
Input: arr = [100,100,99,99]
Output: 4
Example 5:
Input: arr = [7]
Output: 1
Constraints:
1 <= arr.length <= 10^5
1 <= arr[i] <= 100
|
class Solution:
def numOfSubarrays(self, A: List[int]) -> int:
n = len(A)
mod = 10**9+7
ans = 0
prefix, ctr = 0, Counter([0])
for i in range(n):
prefix = prefix+A[i]
s = prefix%2
ans = ans+ctr[1-s]
ans = ans%mod
ctr[s] += 1
return ans
|
Given an array of integers arr. Return the number of sub-arrays with odd sum.
As the answer may grow large, the answer must be computed modulo 10^9 + 7.
Example 1:
Input: arr = [1,3,5]
Output: 4
Explanation: All sub-arrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]]
All sub-arrays sum are [1,4,9,3,8,5].
Odd sums are [1,9,3,5] so the answer is 4.
Example 2:
Input: arr = [2,4,6]
Output: 0
Explanation: All sub-arrays are [[2],[2,4],[2,4,6],[4],[4,6],[6]]
All sub-arrays sum are [2,6,12,4,10,6].
All sub-arrays have even sum and the answer is 0.
Example 3:
Input: arr = [1,2,3,4,5,6,7]
Output: 16
Example 4:
Input: arr = [100,100,99,99]
Output: 4
Example 5:
Input: arr = [7]
Output: 1
Constraints:
1 <= arr.length <= 10^5
1 <= arr[i] <= 100
|
class Solution:
def numOfSubarrays(self, arr: List[int]) -> int:
even, odd = 1, 0
total = 0
ans = 0
for i in arr:
total += i
if total % 2 == 1:
ans += even
odd += 1
else:
ans += odd
even += 1
ans %= 10**9 + 7
return ans
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
# https://leetcode.com/problems/maximum-of-absolute-value-expression/discuss/340075/c%2B%2B-beats-100-(both-time-and-memory)-with-algorithm-and-image
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
N = len(arr1)
a = [arr1[i] + arr2[i] + i for i in range(N)]
b = [arr1[i] + arr2[i] - i for i in range(N)]
c = [arr1[i] - arr2[i] + i for i in range(N)]
d = [arr1[i] - arr2[i] - i for i in range(N)]
return max(
max(x) - min(x)
for x in (a, b, c, d)
)
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
A, B, C, D = [], [], [], []
# https://leetcode.com/problems/maximum-of-absolute-value-expression/discuss/340075/c++-beats-100-(both-time-and-memory)-with-algorithm-and-image
# much easier to understand.
# we need to break the four absolute value and reduce them. We can see there are 8 cases but only 4 cases. We generate 4 arrays and compute max() - min()
for i in range(len(arr1)):
x = arr1[i] + arr2[i] + i
y = arr1[i] - arr2[i] - i
z = arr1[i] + arr2[i] - i
t = arr1[i] - arr2[i] + i
A.append(x)
B.append(y)
C.append(z)
D.append(t)
return max(list([max(x) - min(x) for x in [A, B, C, D]]))
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
n = len(arr1)
points = list(zip(arr1, arr2, range(n)))
funcs = [lambda x, y, i: x + y + i,
lambda x, y, i: x - y - i,
lambda x, y, i: x - y + i,
lambda x, y, i: x + y - i]
res = 0
for func in funcs:
temp = [func(*pt) for pt in points]
res = max(res, max(temp)-min(temp))
return res
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
'''
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
4 cases:
1) arr1[i] > arr1[j] and arr2[i] < arr2[j]
remove abs
arr1[i] - arr1[j] + arr2[j] - arr2[i] + j - i
(arr1[i] - arr2[i] - i) - (arr1[j] - arr2[j] - j)
2) arr1[i] > arr1[j] and arr2[i] > arr2[j]
remove abs
arr1[i] - arr1[j] + arr2[i] - arr2[j] + j - i
(arr1[i] + arr2[i] - i) - (arr1[j] + arr2[j] - j)
3) arr1[i] < arr1[j] and arr2[i] < arr2[j]
remove abs
arr1[j] - arr1[i] + arr2[j] - arr2[i] + j - i
(arr1[j] + arr2[j] + j) - (arr1[i] + arr2[i] + i)
4) arr1[i] < arr1[j] and arr2[i] > arr2[j]
remove abs
arr1[j] - arr1[i] + arr2[i] - arr2[j] + j - i
(arr1[j] - arr2[j] + j) - (arr1[i] - arr2[i] + i)
'''
max1 = max2 = max3 = max4 = float('-inf')
min1 = min2 = min3 = min4 = float('inf')
for i in range(0, len(arr1)):
tmp1 = arr1[i] - arr2[i] - i
max1 = max(max1, tmp1)
min1 = min(min1, tmp1)
tmp2 = arr1[i] + arr2[i] - i
max2 = max(max2, tmp2)
min2 = min(min2, tmp2)
tmp3 = arr1[i] + arr2[i] + i
max3 = max(max3, tmp3)
min3 = min(min3, tmp3)
tmp4 = arr1[i] - arr2[i] + i
max4 = max(max4, tmp4)
min4 = min(min4, tmp4)
return max(max1 - min1, max2 - min2, max3 - min3, max4 - min4)
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
ans=0
mn =10**7
mx=-10**7
mn1 =10**7
mx1=-10**7
mn2 =10**7
mx2=-10**7
mn3 =10**7
mx3=-10**7
for j in range(len(arr1)):
tmp = arr1[j] + arr2[j] + j
tmp1 = arr1[j] - arr2[j] + j
tmp2 = -arr1[j] + arr2[j] + j
tmp3 = -arr1[j] - arr2[j] + j
mn=min(mn,tmp)
mx=max(mx,tmp)
mn1=min(mn1,tmp1)
mx1=max(mx1,tmp1)
mn2=min(mn2,tmp2)
mx2=max(mx2,tmp2)
mn3=min(mn3,tmp3)
mx3=max(mx3,tmp3)
return max((mx-mn),mx1-mn1,mx2-mn2,mx3-mn3)
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
# 1. arr1[i] - arr1[j] + arr2[i] - arr2[j] + i - j => ( arr1[i] + arr2[i] + i) - ( arr1[j] + arr2[j] + j)
# 2. arr1[i] - arr1[j] + arr2[i] - arr2[j] + j - i => ( arr1[i] + arr2[i] - i) - ( arr1[j] + arr2[j] - j)
# 3. arr1[i] - arr1[j] + arr2[j] - arr2[i] + i - j => ( arr1[i] - arr2[i] + i) - ( arr1[j] - arr2[j] + j)
# 4. arr1[i] - arr1[j] + arr2[j] - arr2[i] + j - i => ( arr1[i] - arr2[i] - i) - ( arr1[j] - arr2[j] - j)
# 5. arr1[j] - arr1[i] + arr2[i] - arr2[j] + i - j => (-arr1[i] + arr2[i] + i) - (-arr1[j] + arr2[j] + j)
# 6. arr1[j] - arr1[i] + arr2[i] - arr2[j] + j - i => (-arr1[i] + arr2[i] - i) - (-arr1[j] + arr2[j] - j)
# 7. arr1[j] - arr1[i] + arr2[j] - arr2[i] + i - j => (-arr1[i] - arr2[i] + i) - (-arr1[j] - arr2[j] + j)
# 8. arr1[j] - arr1[i] + arr2[j] - arr2[i] + j - i => (-arr1[i] - arr2[i] - i) - (-arr1[j] - arr2[j] - j)
# min1, max1 for arr1[i] + arr2[i] + i
# min2, max2 for arr1[i] + arr2[i] - i
# min3, max3 for arr1[i] - arr2[i] + i
# min4, max4 for arr1[i] - arr2[i] - i
min1 = min2 = min3 = min4 = float('inf')
max1 = max2 = max3 = max4 = float('-inf')
for i in range(len(arr1)):
s, d = arr1[i]+arr2[i], arr1[i]-arr2[i]
min1, max1 = min(min1, s+i), max(max1, s+i)
min2, max2 = min(min2, s-i), max(max2, s-i)
min3, max3 = min(min3, d+i), max(max3, d+i)
min4, max4 = min(min4, d-i), max(max4, d-i)
return max(max1-min1, max2-min2, max3-min3, max4-min4)
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
x, y, z, w = [], [], [], []
for i in range(len(arr1)):
x.append(arr1[i] + arr2[i] + i)
y.append(arr1[i] + arr2[i] - i)
z.append(arr1[i] - arr2[i] + i)
w.append(arr1[i] - arr2[i] - i)
return max(map(lambda a: max(a) - min(a), (x,y,z,w)))
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def join(self, a: List[int], b: List[int], add=True, ascend=True):
arr = []
for i in range(len(a)):
if add:
arr.append(a[i] + b[i])
else:
arr.append(a[i] - b[i])
if ascend:
arr[i] += i
else:
arr[i] -= i
return arr
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
if not len(arr1):
return 0
mins, maxes = [], []
idx = []
for i, arr in enumerate([self.join(arr1, arr2, add, asc) for add, asc in [(True, True), (True, False), (False, True), (False, False)]]):
mins.append(arr[0])
maxes.append(arr[0])
idx.append((0, 0))
for j in range(1, len(arr)):
if arr[j] < mins[i]:
mins[i] = arr[j]
idx[i] = j, idx[i][1]
if arr[j] > maxes[i]:
maxes[i] = arr[j]
idx[i] = idx[i][0], j
largest_diff = float('-inf')
if (arr1[idx[0][0]] > arr1[idx[0][1]]) == (arr2[idx[0][0]] > arr2[idx[0][1]]) and idx[0][0] <= idx[0][1]:
largest_diff = maxes[0] - mins[0]
if (arr1[idx[1][0]] > arr1[idx[1][1]]) == (arr2[idx[1][0]] > arr2[idx[1][1]]) and idx[1][0] >= idx[1][1]:
largest_diff = max(largest_diff, maxes[1] - mins[1])
if (arr1[idx[2][0]] > arr1[idx[2][1]]) != (arr2[idx[2][0]] > arr2[idx[2][1]]) and idx[2][0] <= idx[2][1]:
largest_diff = max(largest_diff, maxes[2] - mins[2])
if (arr1[idx[3][0]] > arr1[idx[3][1]]) != (arr2[idx[3][0]] > arr2[idx[3][1]]) and idx[3][0] >= idx[3][1]:
largest_diff = max(largest_diff, maxes[3] - mins[3])
return largest_diff
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
#|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
#j>i
#=max(arr1[j]-arr1[i]+arr2[j]-arr2[i]+j-i,
# arr1[i]-arr1[j]+arr2[j]-arr2[i]+j-i,
# arr1[j]-arr1[i]+arr2[i]-arr2[j]+j-i,
# arr1[i]-arr1[j]+arr2[i]-arr2[j]+j-i)
#arrA=arr1+arr2
#arrB=arr2-arr1
#arrC=arr1-arr2
#arrD=-arr1-arr2
#arr?[j]-arr?[i]+j-i
#(arr?[j]+j)-(arr?[i]+i)
arrA=[0]*len(arr1)
arrC=[0]*len(arr1)
arrD=[0]*len(arr1)
arrB=[0]*len(arr1)
for i in range(len(arr1)):
arrA[i]=arr1[i]+arr2[i]+i
arrB[i]=-arr1[i]+arr2[i]+i
arrC[i]=arr1[i]-arr2[i]+i
arrD[i]=-arr1[i]-arr2[i]+i
minA=arrA[0]
minB=arrB[0]
minC=arrC[0]
minD=arrD[0]
res=0
for i in range(1,len(arrA)):
minA=min(minA,arrA[i])
minB=min(minB,arrB[i])
minC=min(minC,arrC[i])
minD=min(minD,arrD[i])
res=max(res,arrA[i]-minA,arrB[i]-minB,arrC[i]-minC,arrD[i]-minD)
return res
dic1A={}
dic2A={}
dic1A={}
dic2A={}
dic2={}
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
# 1. arr1[i] - arr1[j] + arr2[i] - arr2[j] + i - j => ( arr1[i] + arr2[i] + i) - ( arr1[j] + arr2[j] + j)
# 2. arr1[i] - arr1[j] + arr2[i] - arr2[j] + j - i => ( arr1[i] + arr2[i] - i) - ( arr1[j] + arr2[j] - j)
# 3. arr1[i] - arr1[j] + arr2[j] - arr2[i] + i - j => ( arr1[i] - arr2[i] + i) - ( arr1[j] - arr2[j] + j)
# 4. arr1[i] - arr1[j] + arr2[j] - arr2[i] + j - i => ( arr1[i] - arr2[i] - i) - ( arr1[j] - arr2[j] - j)
# 5. arr1[j] - arr1[i] + arr2[i] - arr2[j] + i - j => (-arr1[i] + arr2[i] + i) - (-arr1[j] + arr2[j] + j)
# 6. arr1[j] - arr1[i] + arr2[i] - arr2[j] + j - i => (-arr1[i] + arr2[i] - i) - (-arr1[j] + arr2[j] - j)
# 7. arr1[j] - arr1[i] + arr2[j] - arr2[i] + i - j => (-arr1[i] - arr2[i] + i) - (-arr1[j] - arr2[j] + j)
# 8. arr1[j] - arr1[i] + arr2[j] - arr2[i] + j - i => (-arr1[i] - arr2[i] - i) - (-arr1[j] - arr2[j] - j)
# min1, max1 for arr1[i] + arr2[i] + i
# min2, max2 for arr1[i] + arr2[i] - i
# min3, max3 for arr1[i] - arr2[i] + i
# min4, max4 for arr1[i] - arr2[i] - i
min1 = min2 = min3 = min4 = float('inf')
max1 = max2 = max3 = max4 = float('-inf')
for i, [n1,n2] in enumerate(zip(arr1, arr2)):
min1, max1 = min(min1, n1+n2+i), max(max1, n1+n2+i)
min2, max2 = min(min2, n1+n2-i), max(max2, n1+n2-i)
min3, max3 = min(min3, n1-n2+i), max(max3, n1-n2+i)
min4, max4 = min(min4, n1-n2-i), max(max4, n1-n2-i)
return max(max1-min1, max2-min2, max3-min3, max4-min4)
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
n = len(arr1)
res = 0
for p, q in [(1, 1), (1, -1), (-1, 1), (-1, -1)]:
smallest = p * arr1[0] + q * arr2[0]
for i in range(n):
cur = p * arr1[i] + q * arr2[i] + i
res = max(cur - smallest, res)
smallest = min(smallest, cur)
return res
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
a = [arr1[i] + arr2[i] + i for i in range(len(arr1))]
b = [arr1[i] + arr2[i] - i for i in range(len(arr1))]
c = [arr1[i] - arr2[i] + i for i in range(len(arr1))]
d = [arr1[i] - arr2[i] - i for i in range(len(arr1))]
return max(map(lambda x: max(x) - min(x), (a, b, c, d)))
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
vector = [(1,1),(-1,1),(1,-1),(-1,-1)]
res = 0
sm = float('inf')
for vec in vector:
p,q = vec
sm = float('inf')
for i in range(len(arr1)):
cur = p*arr1[i]+q*arr2[i]+i
res = max(res, cur-sm)
sm = min(cur, sm)
return res
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
res, n = 0, len(arr1)
for p, q in [[1, 1], [1, -1], [-1, 1], [-1, -1]]:
smallest = p * arr1[0] + q * arr2[0] + 0
for i in range(n):
cur = p * arr1[i] + q * arr2[i] + i
res = max(res, cur - smallest)
smallest = min(smallest, cur)
return res
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
n = len(arr1)
a = [arr1[i] + arr2[i] - i for i in range(n)]
mn = 10 ** 20
ans = 0
for i in a[::-1]:
ans = max(ans, i - mn)
mn = min(mn, i)
a = [arr1[i] - arr2[i] - i for i in range(n)]
mn = 10 ** 20
for i in a[::-1]:
ans = max(ans, i - mn)
mn = min(mn, i)
a = [arr1[i] - arr2[i] + i for i in range(n)]
mn = 10 ** 20
for i in a:
ans = max(ans, i - mn)
mn = min(mn, i)
a = [arr1[i] + arr2[i] + i for i in range(n)]
mn = 10 ** 20
for i in a:
ans = max(ans, i - mn)
mn = min(mn, i)
return ans
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
D={}
a1,a2,a3,a4 = -2**31,-2**31,-2**31,-2**31
b1,b2,b3,b4=2**31,2**31,2**31,2**31
for i in range(len(arr1)):
t = arr1[i]+arr2[i]+i
a1 = max(a1,t)
b1 = min(b1,t)
t= arr1[i]+arr2[i]-i
a2 = max(a2,t)
b2 = min(b2,t)
t =arr1[i]-arr2[i]-i
a3 = max(a3,t)
b3 = min(b3,t)
t = arr1[i]-arr2[i]+i
a4 = max(a4,t)
b4 = min(b4,t)
return max(a1-b1,a2-b2,a3-b3,a4-b4)
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
#fix i and test for j
# count arr1 i, arr2 i, ind
minmin = []
minmax = []
maxmin = []
maxmax = []
res = 0
for i,(v1,v2) in enumerate(zip(arr1,arr2)):
if not minmin or minmin[0]-v1+minmin[1]-v2+minmin[2]-i>0:
minmin = [v1,v2,i]
if not minmax or minmax[0]-v1+v2-minmax[1]+minmax[2]-i>0:
minmax = [v1,v2,i]
if not maxmin or v1-maxmin[0]+maxmin[1]-v2+maxmin[2]-i>0:
maxmin = [v1,v2,i]
if not maxmax or v1-maxmax[0]+v2-maxmax[1]+maxmax[2]-i>0:
maxmax = [v1,v2,i]
res = max(res,v1-minmin[0]+v2-minmin[1]+i-minmin[2])
res = max(res,v1-minmax[0]+minmax[1]-v2+i-minmax[2])
res = max(res,maxmin[0]-v1+v2-maxmin[1]+i-maxmin[2])
res = max(res,maxmax[0]-v1+maxmax[1]-v2+i-maxmax[2])
#print(maxmax[0]-v1+maxmax[1]-v2+i-maxmin[2])
#print(minmin,minmax,maxmin,maxmax)
return res
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def calc(self, a, b):
c = [ai+bi for ai, bi in zip(a, b)]
m = 10**18
res = 0
for i in range(len(c)):
m = min(m, c[i]+i)
res = max(res, c[i]+i-m)
return res
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
arr1_ = [-arr1_i for arr1_i in arr1]
arr2_ = [-arr2_i for arr2_i in arr2]
return max(self.calc(arr1, arr2), self.calc(arr1, arr2_), self.calc(arr1_, arr2), self.calc(arr1_, arr2_))
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
#https://t123456ll.github.io/1131.%20Maximum%20of%20Absolute%20Value%20Expression.html
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
max1 = max2 = max3 = max4 = -math.inf
min1 = min2 = min3 = min4 = math.inf
for i in range(len(arr1)):
x = arr1[i]
y = arr2[i]
max1 = max(max1, x+y-i)
min1 = min(min1, x+y-i)
max2 = max(max2, x-y-i)
min2 = min(min2, x-y-i)
max3 = max(max3, -x+y-i)
min3 = min(min3, -x+y-i)
max4 = max(max4, -x-y-i)
min4 = min(min4, -x-y-i)
return max(max1-min1, max2-min2, max3-min3, max4-min4)
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
def expr(sign1, sign2, i):
return sign1*arr1[i]+sign2*arr2[i] + i
def diff(sign1, sign2):
max_ = max(expr(sign1, sign2, i) for i in range(len(arr1)))
min_ = min(expr(sign1, sign2, i) for i in range(len(arr1)))
return max_ - min_
return max(diff(sign1, sign2) for sign1, sign2 in [(1,1),(1,-1),(-1,1),(-1,-1)])
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
res, n = 0, len(arr1)
for x, y in ((1, 1), (1, -1), (-1, 1), (-1, -1)):
mini = x * arr1[0] + y * arr2[0]
for i in range(n):
temp = x * arr1[i] + y * arr2[i] + i
res = max(res, temp - mini)
mini = min(mini, temp)
return res
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1, arr2) -> int:
res = 0
length = len(arr1)
for p, q in [(1,1),(-1,-1),(1,-1),(-1,1)]:
min_v = p*arr1[0] + q*arr2[0] + 0
for i in range(1, length):
v = p*arr1[i] + q*arr2[i] + i
res = max(res, v - min_v)
min_v = min(v, min_v)
return res
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
ans =0
n = len(arr1)
for x, y in [[1,1],[1,-1],[-1,1],[-1,-1]]:
smallest = x*arr1[0] + y*arr2[0] + 0
for i in range(n):
cur = x*arr1[i] + y*arr2[i] + i
ans = max(ans, cur-smallest)
smallest = min(smallest, cur)
return ans
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
x, y = arr1, arr2
maxCase1 = maxCase2 = maxCase3 = maxCase4 = -float('inf')
minCase1 = minCase2 = minCase3 = minCase4 = float('inf')
for i in range(len(x)):
maxCase1 = max(maxCase1, x[i]+y[i]-i)
maxCase2 = max(maxCase2, x[i]-y[i]-i)
maxCase3 = max(maxCase3, -x[i]+y[i]-i)
maxCase4 = max(maxCase4, -x[i]-y[i]-i)
minCase1 = min(minCase1, x[i]+y[i]-i)
minCase2 = min(minCase2, x[i]-y[i]-i)
minCase3 = min(minCase3, -x[i]+y[i]-i)
minCase4 = min(minCase4, -x[i]-y[i]-i)
return max(maxCase1-minCase1, maxCase2-minCase2, maxCase3-minCase3, maxCase4-minCase4)
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
maxsize = 2147483647
min1 = maxsize
min2 = maxsize
max1 = -maxsize-1
max2 = -maxsize -1
min3 = maxsize
min4 = maxsize
max3 = -maxsize-1
max4 = -maxsize -1
for i in range(len(arr1)):
min1 = min(min1, arr1[i]+arr2[i]+i)
max1 = max(max1, arr1[i]+arr2[i]+i)
min2 = min(min2, arr1[i]+arr2[i]-i)
max2 = max(max2, arr1[i]+arr2[i]-i)
min3 = min(min3, arr1[i]-arr2[i]+i)
max3 = max(max3, arr1[i]-arr2[i]+i)
min4 = min(min4, arr1[i]-arr2[i]-i)
max4 = max(max4, arr1[i]-arr2[i]-i)
result = max(max1-min1, max2-min2, max3-min3, max4-min4)
return result
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
mx = 0
for a in [1, -1]:
for b in [1, -1]:
sm = a*arr1[0] + b*arr2[0] + 0
for i in range(1, len(arr1)):
v = a*arr1[i] + b*arr2[i] + i
mx = max(mx, v - sm)
sm = min(sm, v)
return mx
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
max1 = max2 = max3 = max4 = float('-inf')
min1 = min2 = min3 = min4 = float('inf')
for i in range(len(arr1)):
tmp1 = arr1[i] - arr2[i] - i
max1 = max(max1 , tmp1)
min1 = min(min1 , tmp1)
tmp2 = arr1[i] + arr2[i] - i
max2 = max(max2 , tmp2)
min2 = min(min2 , tmp2)
tmp3 = arr1[i] + arr2[i] + i
max3 = max(max3 , tmp3)
min3 = min(min3 , tmp3)
tmp4 = arr1[i] - arr2[i] + i
max4 = max(max4 , tmp4)
min4 = min(min4 , tmp4)
return max((max1 - min1), (max2 - min2),(max3 - min3),(max4 - min4))
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
n = len(arr1)
points = list(zip(arr1, arr2, range(n)))
# Create 4 functions that can give abs value possibilities based on
# whether arr1[i] is larger or smaller than arr1[j] and so on.
funcs = [
lambda x, y, z: x + y + z,
lambda x, y, z: - x + y + z,
lambda x, y, z: x - y + z,
lambda x, y, z: - x - y + z,
]
ans = 0
for func in funcs:
mapped = [func(*p) for p in points]
ans = max(ans, max(mapped) - min(mapped))
return ans
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
ans = 0
for x in (1, -1):
for y in (1,-1):
minn = arr1[0] * x + arr2[0] * y
for i in range(len(arr1)):
curr = arr1[i] * x + arr2[i] * y + i
minn = min(minn, curr)
ans = max(ans, curr - minn)
return ans
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
f1 = lambda i: arr1[i] + arr2[i] + i
f2 = lambda i: -arr1[i] + arr2[i] + i
f3 = lambda i: arr1[i] - arr2[i] + i
f4 = lambda i: -arr1[i] - arr2[i] + i
res = 0
for f in [f1, f2, f3, f4]:
low = float('inf')
high = -float('inf')
for i in range(len(arr1)):
low = min(low, f(i))
high = max(high, f(i))
res = max(res, high - low)
return res
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
A, B, C, D = [], [], [], []
for i in range(len(arr1)):
x = arr1[i] + arr2[i] + i
y = arr1[i] - arr2[i] - i
z = arr1[i] + arr2[i] - i
t = arr1[i] - arr2[i] + i
A.append(x)
B.append(y)
C.append(z)
D.append(t)
return max(list([max(x) - min(x) for x in [A, B, C, D]]))
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
maxVal = 0
cases = [(1,1,1), (1,1,-1), (1,-1,1), (1,-1,-1), (-1,1,1), (-1,1,-1), (-1,-1,-1)]
for case in cases:
a, b, c = case
if c == 1:
minVal = a*arr1[0] + b*arr2[0] + 0
for i in range(1, len(arr1)):
candidate = a*arr1[i] + b*arr2[i] + c*i
maxVal = max(maxVal, candidate - minVal)
minVal = min(minVal, candidate)
else:
minVal = a*arr1[-1] + b*arr2[-1] + c*(len(arr1) - 1)
for i in range(len(arr1) - 2, -1, -1):
candidate = a*arr1[i] + b*arr2[i] + c*i
maxVal = max(maxVal, candidate - minVal)
minVal = min(minVal, candidate)
return maxVal
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def helper(self,sign1, sign2, arr1, arr2):
m1, m2 = -10**7, 10**7
for i in range(len(arr1)):
t = sign1*arr1[i] + sign2*arr2[i] + i
m1 = max(m1,t)
m2 = min(m2,t)
return m1 - m2
def maxAbsValExpr(self, arr1, arr2):
res = 0
res = max(res,self.helper(1,1,arr1,arr2))
res = max(res,self.helper(-1,1,arr1,arr2))
res = max(res,self.helper(1,-1,arr1,arr2))
res = max(res,self.helper(-1,-1,arr1,arr2))
return res
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
n = len(arr1)
# abs(a1[i]-a1[j])+abs(a2[i]-a2[j])
# =max(a1i+a2i-a1j-a2j, a1i-a2i-a1j+a2j,
# -a1i+a2i+a1j-a2j, -a1i-a2i+a1j+a2j)
#
for i in range(n):
arr1[i], arr2[i] = arr1[i]+arr2[i], arr1[i]-arr2[i]
arr11 = [x+i for i,x in enumerate(arr1)]
arr12 = [x-i for i,x in enumerate(arr1)]
arr21 = [x+i for i,x in enumerate(arr2)]
arr22 = [x-i for i,x in enumerate(arr2)]
return max(max(a)-min(a) for a in [arr11,arr12,arr21,arr22])
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
n = len(arr1)
def get_max(arr):
max_val = 0
heap = [] # min_val, min_idx
for idx, val in enumerate(arr):
if heap:
min_val, min_idx = heap[0]
abs_max = val - min_val + idx - min_idx
if abs_max > max_val:
max_val = abs_max
heapq.heappush(heap, (val, idx))
return max_val
max_abs = 0
for first in [-1, 1]:
for second in [-1, 1]:
arr = []
for i in range(n):
arr.append(first * arr1[i] + second * arr2[i])
max_abs = max(get_max(arr), max_abs)
return max_abs
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
n = len(arr1)
ans = float('-inf')
maxx = [float('-inf')] * 4
minn = [float('inf')] * 4
for i in range(n):
maxx[0] = max(maxx[0], arr1[i] + arr2[i] + i)
minn[0] = min(minn[0], arr1[i] + arr2[i] + i)
ans = max(ans, maxx[0] - minn[0])
maxx[1] = max(maxx[1], arr1[i] + arr2[i] - i)
minn[1] = min(minn[1], arr1[i] + arr2[i] - i)
ans = max(ans, maxx[1] - minn[1])
maxx[2] = max(maxx[2], arr1[i] - arr2[i] + i)
minn[2] = min(minn[2], arr1[i] - arr2[i] + i)
ans = max(ans, maxx[2] - minn[2])
maxx[3] = max(maxx[3], arr1[i] - arr2[i] - i)
minn[3] = min(minn[3], arr1[i] - arr2[i] - i)
ans = max(ans, maxx[3] - minn[3])
return ans
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, A: List[int], B: List[int]) -> int:
n = len(A)
max1 = max2 = max3 = max4 = -10**6 - 1
min1 = min2 = min3 = min4 = 10**6 + 1
for i in range(n):
temp = A[i] - B[i] - i
min1 = min(min1,temp)
max1 = max(max1,temp)
temp = A[i] + B[i] - i
min2 = min(min2,temp)
max2 = max(max2,temp)
temp = A[i] + B[i] + i
min3 = min(min3,temp)
max3 = max(max3,temp)
temp = A[i] - B[i] +i
min4 = min(min4,temp)
max4 = max(max4,temp)
ans = max(max4 - min4, max3 - min3, max2 - min2, max1 - min1)
return ans
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
ans = 0
for p, q in [(-1,-1), (1, -1), (-1, 1), (1, 1)]:
min_v = max_v = p*arr1[0] + q*arr2[0]
for i in range(1, len(arr1)):
v = p*arr1[i] + q*arr2[i] + i
min_v = min(min_v, v)
max_v = max(max_v, v)
ans = max(ans, max_v- min_v)
return ans
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
maxVal = 0
cases = [(1,1,1), (1,1,-1), (1,-1,1), (1,-1,-1), (-1,1,1), (-1,1,-1), (-1,-1,-1)]
for case in cases:
a, b, c = case
minimum, maximum = float('inf'), float('-inf')
for i in range(0, len(arr1)):
minimum = min(minimum, a*arr1[i] + b*arr2[i] + c*i)
maximum = max(maximum, a*arr1[i] + b*arr2[i] + c*i)
maxVal = max(maxVal, maximum - minimum)
return maxVal
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
maxMax = (arr1[0] + arr2[0], 0)
minMin = (-arr1[0] - arr2[0], 0)
minMax = (-arr1[0] + arr2[0], 0)
maxMin = (arr1[0] - arr2[0], 0)
table = [maxMax, minMin, minMax, maxMin]
n = len(arr1)
ans = 0
for i in range(1, n):
for k in range(4):
_, j = table[k]
ans = max(ans, abs(arr1[i]-arr1[j])+abs(arr2[i]-arr2[j])+i-j)
if k == 0:
newSum = arr1[i] + arr2[i]
elif k == 1:
newSum = -arr1[i] - arr2[i]
elif k == 2:
newSum = -arr1[i] + arr2[i]
elif k == 3:
newSum = arr1[i] - arr2[i]
if newSum -1 > table[k][0]:
table[k] = (newSum, i)
else:
table[k] = (table[k][0]+1, table[k][1])
return ans
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
x = [arr1[i] + arr2[i] + i for i in range(len(arr1))]
y = [arr1[i] + arr2[i] - i for i in range(len(arr1))]
z = [arr1[i] - arr2[i] + i for i in range(len(arr1))]
w = [arr1[i] - arr2[i] - i for i in range(len(arr1))]
return max(map(lambda a: max(a) - min(a), (x,y,z,w)))
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
n = len(arr1)
def get_max(arr):
max_val = 0
min_val, min_idx = float('inf'), float('inf')
for idx, val in enumerate(arr):
if min_idx < float('inf'):
abs_max = val - min_val + idx - min_idx
if abs_max > max_val:
max_val = abs_max
if val + idx < min_val + min_idx:
min_val, min_idx = val, idx
return max_val
max_abs = 0
for first in [-1, 1]:
for second in [-1, 1]:
arr = []
for i in range(n):
arr.append(first * arr1[i] + second * arr2[i])
max_abs = max(get_max(arr), max_abs)
return max_abs
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
maxVal = 0
cases = [(1,1,1), (1,1,-1), (1,-1,1), (1,-1,-1), (-1,1,1), (-1,1,-1), (-1,-1,-1)]
for case in cases:
a, b, c = case
minimum, maximum = a*arr1[0] + b*arr2[0] + 0, a*arr1[0] + b*arr2[0] + 0
for i in range(1, len(arr1)):
minimum = min(minimum, a*arr1[i] + b*arr2[i] + c*i)
maximum = max(maximum, a*arr1[i] + b*arr2[i] + c*i)
maxVal = max(maxVal, maximum - minimum)
# if c == 1:
# minVal = a*arr1[0] + b*arr2[0] + 0
# for i in range(1, len(arr1)):
# candidate = a*arr1[i] + b*arr2[i] + c*i
# maxVal = max(maxVal, candidate - minVal)
# minVal = min(minVal, candidate)
# else:
# minVal = a*arr1[-1] + b*arr2[-1] + c*(len(arr1) - 1)
# for i in range(len(arr1) - 2, -1, -1):
# candidate = a*arr1[i] + b*arr2[i] + c*i
# maxVal = max(maxVal, candidate - minVal)
# minVal = min(minVal, candidate)
return maxVal
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
n = len(arr1)
points = list(zip(arr1, arr2, list(range(n))))
funcs = [
lambda x, y, z: x + y + z,
lambda x, y, z: x + y - z,
lambda x, y, z: x - y + z,
lambda x, y, z: x - y - z,
]
result = 0
for func in funcs:
mapped = [func(*p) for p in points]
result = max(result, max(mapped) - min(mapped))
return result
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
def getValue(arr):
return max(arr) - min(arr)
v1 = [0]*len(arr1)
v2 = [0]*len(arr1)
v3 = [0]*len(arr1)
v4 = [0]*len(arr1)
for i in range(len(arr1)):
v1[i] = arr1[i] + arr2[i] + i
v2[i] = arr1[i] + arr2[i] - i
v3[i] = arr1[i] - arr2[i] + i
v4[i] = arr1[i] - arr2[i] - i
return max(getValue(v1), getValue(v2), getValue(v3), getValue(v4))
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
n = len(arr1)
ma = [float('-inf')] * 4
res =[float('-inf')] * 4
for i in range(n-1,-1,-1):
a = [arr1[i] - arr2[i] + i,arr1[i] + arr2[i] + i,-arr1[i] + arr2[i] + i,-arr1[i] -arr2[i] + i]
for j in range(4):
res[j] = max(res[j], ma[j] - a[j])
for j in range(4):
ma[j] = max(ma[j], a[j])
return max(res)
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
case_1_max = case_2_max = case_3_max = case_4_max = -float('inf')
case_1_min = case_2_min = case_3_min = case_4_min = float('inf')
for i in range(len(arr1)):
case_1_max = max(case_1_max, arr1[i] + arr2[i] - i)
case_1_min = min(case_1_min, arr1[i] + arr2[i] - i)
case_2_max = max(case_2_max, arr1[i] - arr2[i] - i)
case_2_min = min(case_2_min, arr1[i] - arr2[i] - i)
case_3_max = max(case_3_max, arr2[i] - arr1[i] - i)
case_3_min = min(case_3_min, arr2[i] - arr1[i] - i)
case_4_max = max(case_4_max, arr2[i] + arr1[i] + i)
case_4_min = min(case_4_min, arr2[i] + arr1[i] + i)
return max(case_1_max - case_1_min,case_2_max - case_2_min,case_3_max - case_3_min,case_4_max - case_4_min)
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
ans = -math.inf
n = len(arr1)
for a in (-1, 1):
for b in (-1, 1):
for c in (-1, 1):
x = -math.inf
y = math.inf
for i, v in enumerate(arr1):
x = max(x, a*i + b*v + c*arr2[i])
y = min(y, a*i + b*v + c*arr2[i])
ans = max(ans, x - y)
return ans
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, a1: List[int], a2: List[int]) -> int:
s1=[]
s2=[]
d1=[]
d2=[]
for i in range(len(a1)):
s1.append(a1[i]+a2[i]+i)
s2.append(a1[i]+a2[i]-i)
d1.append(a1[i]-a2[i]+i)
d2.append(a1[i]-a2[i]-i)
return max(max(s1)-min(s1),max(s2)-min(s2),max(d1)-min(d1),max(d2)-min(d2))
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
n = len(arr1)
res = 0
for p,q in [[1,-1],[-1,1],[1,1],[-1,-1]]:
smallest = p * arr1[0] + q * arr2[0] + 0
for i in range(1,n):
x = arr1[i]*p+arr2[i]*q+i
res = max(res,x-smallest)
smallest = min(smallest,x)
return res
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
c1 = [-9999999999999,-9999999999999,-1]
c2 = [-9999999999999,-9999999999999,-1]
c3 = [-9999999999999,-9999999999999,-1]
c4 = [-9999999999999,-9999999999999,-1]
c5 = [-9999999999999,-9999999999999,-1]
c6 = [-9999999999999,-9999999999999,-1]
c7 = [-9999999999999,-9999999999999,-1]
c8 = [-9999999999999,-9999999999999,-1]
lim = len(arr1)
for i in range(0,lim):
if arr1[i]+arr2[i]+i>c1[0]:
c1[0]=arr1[i]+arr2[i]+i
c1[2]=i
if arr1[i]-arr2[i]+i>c2[0]:
c2[0]=arr1[i]-arr2[i]+i
c2[2]=i
if -arr1[i]-arr2[i]+i>c3[0]:
c3[0]=-arr1[i]-arr2[i]+i
c3[2]=i
if -arr1[i]+arr2[i]+i>c4[0]:
c4[0]=-arr1[i]+arr2[i]+i
c4[2]=i
if arr1[i]+arr2[i]-i>c5[0]:
c5[0]=arr1[i]+arr2[i]-i
c5[2]=i
if arr1[i]-arr2[i]-i>c6[0]:
c6[0]=arr1[i]-arr2[i]-i
c6[2]=i
if -arr1[i]-arr2[i]-i>c7[0]:
c7[0]=-arr1[i]-arr2[i]-i
c7[2]=i
if -arr1[i]+arr2[i]-i>c8[0]:
c8[0]=-arr1[i]+arr2[i]-i
c8[2]=i
###print(c1,c2,c3,c4,c5,c6,c7,c8)
for i in range(0,lim):
if -arr1[i]-arr2[i]-i>c1[1] and i!=c1[2]:
c1[1]=-arr1[i]-arr2[i]-i
if -arr1[i]+arr2[i]-i>c2[1] and i!=c2[2]:
c2[1]=-arr1[i]+arr2[i]-i
if arr1[i]+arr2[i]-i>c3[1] and i!=c3[2]:
c3[1]=arr1[i]+arr2[i]-i
if arr1[i]-arr2[i]-i>c4[1] and i!=c4[2]:
c4[1]=arr1[i]-arr2[i]-i
if -arr1[i]-arr2[i]+i>c5[1] and i!=c5[2]:
c5[1]=-arr1[i]-arr2[i]+i
if -arr1[i]+arr2[i]+i>c6[1] and i!=c6[2]:
c6[1]=-arr1[i]+arr2[i]+i
if arr1[i]+arr2[i]+i>c7[1] and i!=c7[2]:
c7[1]=arr1[i]+arr2[i]+i
if arr1[i]-arr2[i]+i>c8[1] and i!=c8[2]:
c8[1]=arr1[i]-arr2[i]+i
###print(c1,c2,c3,c4,c5,c6,c7,c8)
v1 = 0
if -9999999999999 not in c1:
v1 = c1[0]+c1[1]
v2 = 0
if -9999999999999 not in c2:
v2 = c2[0]+c2[1]
v3 = 0
if -9999999999999 not in c3:
v3 = c3[0]+c3[1]
v4 = 0
if -9999999999999 not in c4:
v4 = c4[0]+c4[1]
v5 = 0
if -9999999999999 not in c5:
v5 = c5[0]+c5[1]
v6 = 0
if -9999999999999 not in c6:
v6 = c6[0]+c6[1]
v7 = 0
if -9999999999999 not in c7:
v7 = c7[0]+c7[1]
v8 = 0
if -9999999999999 not in c8:
v8 = c8[0]+c8[1]
print((v1,v2,v3,v4,v5,v6,v7,v8))
return max(v1,v2,v3,v4,v5,v6,v7,v8)
|
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Constraints:
2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
|
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
if not arr1 or not arr2:
return 0
n = len(arr1)
l1, l2 ,l3, l4 = [], [], [], []
for i in range(len(arr1)):
l1 += [arr1[i]+arr2[i]+i]
l2 += [arr1[i]-arr2[i]+i]
l3 += [-arr1[i]+arr2[i]+i]
l4 += [-arr1[i]-arr2[i]+i]
res = []
res += [max(l1)-min(l1)]
res += [max(l2) -min(l2)]
res += [max(l3)-min(l3)]
res += [max(l4)-min(l4)]
return max(res)
|
Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks.Tasks could be done without original order. Each task could be done in one interval. For each interval, CPU could finish one task or just be idle.
However, there is a non-negative cooling interval n that means between two same tasks, there must be at least n intervals that CPU are doing different tasks or just be idle.
You need to return the least number of intervals the CPU will take to finish all the given tasks.
Example 1:
Input: tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.
Note:
The number of tasks is in the range [1, 10000].
The integer n is in the range [0, 100].
|
class Solution:
def leastInterval(self, tasks, n):
"""
:type tasks: List[str]
:type n: int
:rtype: int
"""
if n == 0: return len(tasks)
from collections import Counter
counter = Counter(tasks)
window = n + 1
biggest_freq = max(list(counter.values()))
num_of_max_freq = list(counter.values()).count(biggest_freq)
return max(window * (biggest_freq - 1) + num_of_max_freq, len(tasks))
|
Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks.Tasks could be done without original order. Each task could be done in one interval. For each interval, CPU could finish one task or just be idle.
However, there is a non-negative cooling interval n that means between two same tasks, there must be at least n intervals that CPU are doing different tasks or just be idle.
You need to return the least number of intervals the CPU will take to finish all the given tasks.
Example 1:
Input: tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.
Note:
The number of tasks is in the range [1, 10000].
The integer n is in the range [0, 100].
|
class Solution:
def leastInterval(self, tasks, n):
"""
:type tasks: List[str]
:type n: int
:rtype: int
"""
if not tasks:
return 0
counts = {}
for i in tasks:
if i in counts:
counts[i] += 1
else:
counts[i] = 1
M = max(counts.values())
Mct = sum([1 for i in counts if counts[i] == M])
return max(len(tasks), (M - 1) * (n + 1) + Mct)
|
Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks.Tasks could be done without original order. Each task could be done in one interval. For each interval, CPU could finish one task or just be idle.
However, there is a non-negative cooling interval n that means between two same tasks, there must be at least n intervals that CPU are doing different tasks or just be idle.
You need to return the least number of intervals the CPU will take to finish all the given tasks.
Example 1:
Input: tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.
Note:
The number of tasks is in the range [1, 10000].
The integer n is in the range [0, 100].
|
class Solution:
def leastInterval(self, tasks, n):
"""
:type tasks: List[str]
:type n: int
:rtype: int
"""
l,dic=len(tasks),{}
for c in tasks:
if c in dic:
dic[c]+=1
else:
dic[c]=1
m,a=max(dic.values()),0
for c in dic:
if dic[c]==m:
a+=1
return max(l,(m-1)*(n+1)+a)
|
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return the number of distinct solutions to the n-queens puzzle.
Example:
Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
|
class Solution:
def totalNQueens(self, n):
def dfs(lst, xy_dif, xy_sum):
p=len(lst)
if p==n: res.append(lst)
for q in range(n):
if (q not in lst) and (p-q not in xy_dif) and (p+q not in xy_sum):
dfs(lst+[q], xy_dif+[p-q], xy_sum +[p+q])
res=[]
dfs([],[],[])
return len(res)
|
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return the number of distinct solutions to the n-queens puzzle.
Example:
Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
|
class Solution:
def totalNQueens(self, n):
"""
:type n: int
:rtype: int
"""
result=[]
self.DFS(n,0,"",[],[],[],result)
print(result)
return len(result)
def DFS(self, n, row, sss, check_col,check_diag1,check_diag2, result):
""" sss is solution string, all other checks are checks for occupied places """
if (len(sss) == n):
result.append('.')
return
for col in range(0,n):
if (col in check_col): continue
if (row+col in check_diag1): continue
if (row-col in check_diag2): continue
self.DFS(n, row+1, sss+str(col), check_col+[col],
check_diag1+[row+col], check_diag2+[row-col],result)
|
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return the number of distinct solutions to the n-queens puzzle.
Example:
Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
|
class Solution:
def totalNQueens(self, n):
"""
:type n: int
:rtype: int
"""
placement = []
def can_place_queen(row, col):
for i, j in enumerate(placement):
if col == j or abs(col - j) == row - i:
# Same column as, or diagonally from other queen
return False
return True
def place_in_row(row):
if row == n:
return 1
count = 0
for col in range(n):
if can_place_queen(row, col):
placement.append(col)
count += place_in_row(row + 1)
placement.pop()
return count
return place_in_row(0)
|
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return the number of distinct solutions to the n-queens puzzle.
Example:
Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
|
class Solution:
def totalNQueens(self, n):
"""
:type n: int
:rtype: int
"""
rl=[0]
col=[False for x in range(n)]
dia1=[False for x in range(2*n-1)]
dia2=[False for x in range(2*n-1)]
self.putQueen(n,col,dia1,dia2,rl,0)
return rl[0]
def putQueen(self,n,col,dia1,dia2,rl,index):
if index==n:
rl[0]+=1
return True
for i in range(n):
if not col[i] and not dia1[index+i] and not dia2[index-i+n-1]:
col[i]=True
dia1[index+i]=True
dia2[index-i+n-1]=True
self.putQueen(n,col,dia1,dia2,rl,index+1)
col[i]=False
dia1[index+i]=False
dia2[index-i+n-1]=False
|
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return the number of distinct solutions to the n-queens puzzle.
Example:
Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
|
class Solution:
def totalNQueens(self, n):
"""
:type n: int
:rtype: int
"""
if n <= 0:
return 0
diag_lr = [True] * (2*n-1)
diag_rl = [True] * (2*n-1)
vert = [True] * n
res = []
def _check_board(x, y):
return vert[y] and diag_lr[y-x+n-1] and diag_rl[x+y]
def _helper(x):
if x == n:
res.append(1)
return
for y in range(n):
if _check_board(x, y):
vert[y] = False
diag_lr[y-x+n-1] = False
diag_rl[x+y] = False
_helper(x+1)
vert[y] = True
diag_lr[y-x+n-1] = True
diag_rl[x+y] = True
_helper(0)
return len(res)
|
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return the number of distinct solutions to the n-queens puzzle.
Example:
Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
|
class Solution:
def __init__(self):
self.board = []
self.col_status = []
self.row_status = []
self.dia_status_1 = []
self.dia_status_2 = []
self.result = 0
def placeQueen(self, row, n):
if row == n:
tmp = [''.join(el) for el in self.board]
self.result += 1
return
for i in range(n):
if self.col_status[i] and self.dia_status_1[i+row] and self.dia_status_2[row-i]:
self.board[row][i] = 'Q'
self.col_status[i] = False
self.dia_status_1[i+row] = False
self.dia_status_2[row-i] = False
self.placeQueen(row+1, n)
self.board[row][i] = '.'
self.col_status[i] = True
self.dia_status_1[i+row] = True
self.dia_status_2[row-i] = True
def totalNQueens(self, n):
"""
:type n: int
:rtype: List[List[str]]
"""
self.board = [['.' for i in range(n)] for j in range(n)]
self.col_status = [True for i in range(n)]
self.row_status = [True for i in range(n)]
self.dia_status_1 = [True for i in range(2*n-1)]
self.dia_status_2 = [True for i in range(2*n-1)]
self.placeQueen(0, n)
return self.result
|
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return the number of distinct solutions to the n-queens puzzle.
Example:
Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
|
class Solution:
def totalNQueens(self, n):
"""
:type n: int
:rtype: int
"""
ans = []
def dfs(queens, xy_dif, xy_sum):
p = len(queens)
if p == n:
result.append(queens)
return None
for q in range(n):
if q not in queens and p-q not in xy_dif and p+q not in xy_sum:
dfs(queens+[q], xy_dif+[p-q], xy_sum+[p+q])
result = []
dfs([], [], [])
return len(result)
|
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return the number of distinct solutions to the n-queens puzzle.
Example:
Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
|
class Solution:
def totalNQueens(self, n):
"""
:type n: int
:rtype: int
"""
def dfs(cols, diag_45, diag_135, depth=0):
nonlocal result
row = len(cols)
if row == n:
result += 1
return
for col in range(n):
if col not in cols and (row - col) not in diag_45 and (row + col) not in diag_135:
dfs(cols + [col], diag_45 + [row - col], diag_135 + [row + col], depth + 1)
result = 0
dfs([], [], [])
return result
|
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return the number of distinct solutions to the n-queens puzzle.
Example:
Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
|
class Solution:
def find_arrangements(self, arrangement, diag1_used, diag2_used, col_used, x, n):
if x == n:
return 1
res = 0
for y in range(n):
diag1 = x + y
diag2 = x - y + n
if not diag1_used[diag1] and not diag2_used[diag2] and not col_used[y]:
arrangement.append(y)
diag1_used[diag1] = True
diag2_used[diag2] = True
col_used[y] = True
cur_res = self.find_arrangements(arrangement, diag1_used, diag2_used, col_used, x + 1, n)
arrangement.pop()
diag1_used[diag1] = False
diag2_used[diag2] = False
col_used[y] = False
res += cur_res
return res
def totalNQueens(self, n):
"""
:type n: int
:rtype: int
"""
arrangement = []
diag1_used = [False] * (2 * n)
diag2_used = [False] * (2 * n)
col_used = [False] * n
return self.find_arrangements(arrangement, diag1_used, diag2_used, col_used, 0, n)
|
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return the number of distinct solutions to the n-queens puzzle.
Example:
Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
|
class Solution:
def totalNQueens(self, n):
"""
:type n: int
:rtype: int
"""
count = 0
def solve(rows, cols, diag0, diag1, n):
nonlocal count
freerows = {i for i in range(n)} - rows
if not freerows:
count += 1
return
i = freerows.pop()
candidates = []
for j in range(n):
if j in cols:
continue
if i + j in diag0:
continue
if i - j in diag1:
continue
rows.add(i)
cols.add(j)
diag0.add(i+j)
diag1.add(i-j)
solve(rows, cols, diag0, diag1, n)
rows.remove(i)
cols.remove(j)
diag0.remove(i+j)
diag1.remove(i-j)
solve(set(), set(), set(), set(), n)
return count
|
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return the number of distinct solutions to the n-queens puzzle.
Example:
Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
|
class Solution:
def totalNQueens(self, n):
"""
:type n: int
:rtype: int
"""
row = [x for x in range(n)]
table = []
for i in range(n):
table.append(row.copy())
result = self.solve(table,0)
return len(result)
def solve(self,table,n):
if table[n]==[]:return []
elif n==len(table)-1:
table[n] = table[n][0]
return [table]
else:
result=[]
for x in table[n]:
table1 = [(x if type(x)==int else x.copy()) for x in table]
table1[n] = x
for row in range(n+1,len(table)):
if x in table1[row]:
table1[row].remove(x)
if x+row-n in table1[row]:
table1[row].remove(x+row-n)
if x-(row-n) in table1[row]:
table1[row].remove(x-(row-n))
result.extend(self.solve(table1,n+1))
return result
|
You are given an array x of n positive numbers. You start at point (0,0) and moves x[0] metres to the north, then x[1] metres to the west,
x[2] metres to the south,
x[3] metres to the east and so on. In other words, after each move your direction changes
counter-clockwise.
Write a one-pass algorithm with O(1) extra space to determine, if your path crosses itself, or not.
Example 1:
Given x = [2, 1, 1, 2],
?????
? ?
???????>
?
Return true (self crossing)
Example 2:
Given x = [1, 2, 3, 4],
????????
? ?
?
?
?????????????>
Return false (not self crossing)
Example 3:
Given x = [1, 1, 1, 1],
?????
? ?
?????>
Return true (self crossing)
Credits:Special thanks to @dietpepsi for adding this problem and creating all test cases.
|
class Solution:
def isSelfCrossing(self, x):
"""
:type x: List[int]
:rtype: bool
"""
if not x or len(x) < 4:
return False
i = 3
while i < len(x):
#print(i)
if x[i] >= x[i-2] and x[i-1] <= x[i-3]:
print('case 1')
return True
elif i >= 4 and x[i-1] == x[i-3] and x[i] + x[i-4] >= x[i-2]:
print('case 2')
return True
elif i >= 5 and x[i-4] < x[i-2] <= x[i] + x[i-4] and x[i-1] <= x[i-3] <= x[i] + x[i-5]:
print('case 3')
return True
i += 1
return False
|
You are given an array x of n positive numbers. You start at point (0,0) and moves x[0] metres to the north, then x[1] metres to the west,
x[2] metres to the south,
x[3] metres to the east and so on. In other words, after each move your direction changes
counter-clockwise.
Write a one-pass algorithm with O(1) extra space to determine, if your path crosses itself, or not.
Example 1:
Given x = [2, 1, 1, 2],
?????
? ?
???????>
?
Return true (self crossing)
Example 2:
Given x = [1, 2, 3, 4],
????????
? ?
?
?
?????????????>
Return false (not self crossing)
Example 3:
Given x = [1, 1, 1, 1],
?????
? ?
?????>
Return true (self crossing)
Credits:Special thanks to @dietpepsi for adding this problem and creating all test cases.
|
class Solution:
def isSelfCrossing(self, x):
"""
:type x: List[int]
:rtype: bool
"""
b = c = d = e = 0
for a in x:
if d >= b > 0 and (a >= c or a >= c-e >= 0 and f >= d-b):
return True
b, c, d, e, f = a, b, c, d, e
return False
|
You are given an array x of n positive numbers. You start at point (0,0) and moves x[0] metres to the north, then x[1] metres to the west,
x[2] metres to the south,
x[3] metres to the east and so on. In other words, after each move your direction changes
counter-clockwise.
Write a one-pass algorithm with O(1) extra space to determine, if your path crosses itself, or not.
Example 1:
Given x = [2, 1, 1, 2],
?????
? ?
???????>
?
Return true (self crossing)
Example 2:
Given x = [1, 2, 3, 4],
????????
? ?
?
?
?????????????>
Return false (not self crossing)
Example 3:
Given x = [1, 1, 1, 1],
?????
? ?
?????>
Return true (self crossing)
Credits:Special thanks to @dietpepsi for adding this problem and creating all test cases.
|
class Solution:
def isSelfCrossing(self, x):
"""
:type x: List[int]
:rtype: bool
"""
n = len(x)
if n < 4:
return False
i = 3
while i < n:
if x[i] >= x[i - 2] and x[i - 3] >= x[i - 1]:
return True
if i >= 4:
if x[i - 1] == x[i - 3] and x[i] + x[i - 4] >= x[i - 2]:
return True
if i >= 5:
if x[i] >= x[i - 2] - x[i - 4] >= 0 and x[i - 5] >= x[i - 3] - x[i - 1] >= 0:
return True
i += 1
return False
|
You are given an array x of n positive numbers. You start at point (0,0) and moves x[0] metres to the north, then x[1] metres to the west,
x[2] metres to the south,
x[3] metres to the east and so on. In other words, after each move your direction changes
counter-clockwise.
Write a one-pass algorithm with O(1) extra space to determine, if your path crosses itself, or not.
Example 1:
Given x = [2, 1, 1, 2],
?????
? ?
???????>
?
Return true (self crossing)
Example 2:
Given x = [1, 2, 3, 4],
????????
? ?
?
?
?????????????>
Return false (not self crossing)
Example 3:
Given x = [1, 1, 1, 1],
?????
? ?
?????>
Return true (self crossing)
Credits:Special thanks to @dietpepsi for adding this problem and creating all test cases.
|
class Solution:
def isSelfCrossing(self, x):
"""
:type x: List[int]
:rtype: bool
"""
l = (len(x))
iscross = False
if l < 4: return False
for i in range(3, l):
#情况1
if x[i-3]>=x[i-1] and x[i-2]<=x[i]:
return True
#情况2
if i>=4 and x[i-4]+x[i]>=x[i-2] and x[i-3]==x[i-1]:
return True
#情况3
if i>=5 and x[i-5]+x[i-1]>=x[i-3] and x[i-4]+x[i]>=x[i-2] and x[i-2]>=x[i-4] and x[i-2]>x[i-4] and x[i-3]>x[i-5] and x[i-1]<x[i-3]:
return True
iscross = False
return iscross
|
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.
The array may contain duplicates.
Example 1:
Input: [1,3,5]
Output: 1
Example 2:
Input: [2,2,2,0,1]
Output: 0
Note:
This is a follow up problem to Find Minimum in Rotated Sorted Array.
Would allow duplicates affect the run-time complexity? How and why?
|
class Solution:
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
min = nums[0]
start, end = 0, len(nums) - 1
while start<end:
mid = (start+end)//2
if nums[mid]>nums[end]:
start = mid+1
elif nums[mid]<nums[end]:
end = mid
else:
end = end - 1
return nums[start]
|
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.
The array may contain duplicates.
Example 1:
Input: [1,3,5]
Output: 1
Example 2:
Input: [2,2,2,0,1]
Output: 0
Note:
This is a follow up problem to Find Minimum in Rotated Sorted Array.
Would allow duplicates affect the run-time complexity? How and why?
|
class Solution:
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
#类似上一题
if not nums:
return -1
l,r=0,len(nums)-1
#二分
while l<=r:
mid=(l+r)//2
# 后半递增
if nums[mid]<nums[r]:
r=mid
else:
#类似上一题
if nums[mid]>nums[r]:
l=mid+1
#这里处理重复数
else:
r-=1
if nums[l]<nums[r]:
return nums[l]
else:
return nums[r]
|
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.
The array may contain duplicates.
Example 1:
Input: [1,3,5]
Output: 1
Example 2:
Input: [2,2,2,0,1]
Output: 0
Note:
This is a follow up problem to Find Minimum in Rotated Sorted Array.
Would allow duplicates affect the run-time complexity? How and why?
|
class Solution(object):
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1:
return nums.pop()
start, finish = 1, len(nums) - 1
while start < finish:
half = (start + finish) // 2
if nums[half] > nums[0]:
start = half + 1
elif nums[half] == nums[0]:
return min(Solution.findMin(self, nums[:half]), Solution.findMin(self, nums[half:]))
else:
finish = half
return min(nums[start], nums[0])
|
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.
The array may contain duplicates.
Example 1:
Input: [1,3,5]
Output: 1
Example 2:
Input: [2,2,2,0,1]
Output: 0
Note:
This is a follow up problem to Find Minimum in Rotated Sorted Array.
Would allow duplicates affect the run-time complexity? How and why?
|
class Solution:
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
if n == 0: return None
l, r = 0, n
while l + 1 < r:
mid = (l + r) >> 1
if nums[mid] == nums[l]:
for i in range(l+1, mid):
if nums[i] < nums[l]:
r = mid
break
if r != mid:
l = mid
elif nums[mid] > nums[l]:
l = mid
else:
r = mid
return nums[r % n]
|
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.
The array may contain duplicates.
Example 1:
Input: [1,3,5]
Output: 1
Example 2:
Input: [2,2,2,0,1]
Output: 0
Note:
This is a follow up problem to Find Minimum in Rotated Sorted Array.
Would allow duplicates affect the run-time complexity? How and why?
|
class Solution:
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
min = 99999999999
if (len(nums)==1):
return nums[0]
for i in range(len(nums)-1):
if nums[i]>=nums[i+1] and min>nums[i+1]:
min= nums[i+1]
elif nums[i]<=nums[i+1] and min>nums[i]:
min= nums[i]
return min
|
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.
The array may contain duplicates.
Example 1:
Input: [1,3,5]
Output: 1
Example 2:
Input: [2,2,2,0,1]
Output: 0
Note:
This is a follow up problem to Find Minimum in Rotated Sorted Array.
Would allow duplicates affect the run-time complexity? How and why?
|
class Solution:
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1:
return nums[0]
for index in range(-1, len(nums) - 1):
if nums[index] > nums[index+1]:
return nums[index+1]
if index + 1 == len(nums) - 1:
return nums[0]
return None
|
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.
The array may contain duplicates.
Example 1:
Input: [1,3,5]
Output: 1
Example 2:
Input: [2,2,2,0,1]
Output: 0
Note:
This is a follow up problem to Find Minimum in Rotated Sorted Array.
Would allow duplicates affect the run-time complexity? How and why?
|
class Solution:
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
start = 0
end = len(nums) - 1
while start < end:
if start < len(nums) - 1 and nums[start] == nums[start + 1]:
start += 1
continue
if nums[end] == nums[end - 1]:
end -= 1
continue
mid = start + (end - start) // 2
if nums[mid] > nums[end]:
start = mid + 1
else:
end = mid
return nums[start]
|
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.
The array may contain duplicates.
Example 1:
Input: [1,3,5]
Output: 1
Example 2:
Input: [2,2,2,0,1]
Output: 0
Note:
This is a follow up problem to Find Minimum in Rotated Sorted Array.
Would allow duplicates affect the run-time complexity? How and why?
|
class Solution:
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 0:
return -1
if nums[len(nums) - 1] > nums[0]:
return nums[0]
start = 0
end = len(nums) - 1
while start + 1 < end:
mid = start + (end - start) // 2
if nums[mid] == nums[start]:
start += 1
elif nums[mid] == nums[end]:
end -= 1
elif nums[mid] > nums[start] and nums[mid] > nums[end]:
start = mid
else:
end = mid
return min(nums[start], nums[end])
|
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.
The array may contain duplicates.
Example 1:
Input: [1,3,5]
Output: 1
Example 2:
Input: [2,2,2,0,1]
Output: 0
Note:
This is a follow up problem to Find Minimum in Rotated Sorted Array.
Would allow duplicates affect the run-time complexity? How and why?
|
class Solution:
def findMin(self, nums):
l = 0
r = len(nums) - 1
res = nums[r]
while l < r:
if nums[l] < nums[r]:
return min(nums[l],res)
res = min(res,nums[r])
m = int((l+r)/2)
if nums[l] == nums[r]:
temp = nums[r]
while nums[l] == temp and l < r:
l = l + 1
while nums[r] == temp and l < r:
r = r - 1
elif nums[m] >= nums[l]:
l = m + 1
elif nums[m] <= nums[r]:
res = min(nums[m],res)
r = m - 1
return min(nums[l],res)
"""
:type nums: List[int]
:rtype: int
"""
|
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.
The array may contain duplicates.
Example 1:
Input: [1,3,5]
Output: 1
Example 2:
Input: [2,2,2,0,1]
Output: 0
Note:
This is a follow up problem to Find Minimum in Rotated Sorted Array.
Would allow duplicates affect the run-time complexity? How and why?
|
class Solution:
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
#类似上一题
if not nums:
return -1
l,r=0,len(nums)-1
#二分
while l<=r:
mid=(l+r)//2
#后半递增
if nums[mid]<nums[r]:
r=mid
else:
#类似上一题
if nums[mid]>nums[r]:
l=mid+1
else:
r-=1
if nums[l]<nums[r]:
return nums[l]
else:
return nums[r]
|
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.
The array may contain duplicates.
Example 1:
Input: [1,3,5]
Output: 1
Example 2:
Input: [2,2,2,0,1]
Output: 0
Note:
This is a follow up problem to Find Minimum in Rotated Sorted Array.
Would allow duplicates affect the run-time complexity? How and why?
|
class Solution:
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1:
return nums[0]
minimun = nums[0]
for i in range(0, len(nums)-1):
if nums[i+1] >= nums[i]:
continue
else:
minimun = nums[i+1]
return minimun
|
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.
The array may contain duplicates.
Example 1:
Input: [1,3,5]
Output: 1
Example 2:
Input: [2,2,2,0,1]
Output: 0
Note:
This is a follow up problem to Find Minimum in Rotated Sorted Array.
Would allow duplicates affect the run-time complexity? How and why?
|
class Solution:
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
min_n = nums[0]
for n in nums:
if n < min_n:
min_n = n
return min_n
|
You have n tiles, where each tile has one letter tiles[i] printed on it.
Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.
Example 1:
Input: tiles = "AAB"
Output: 8
Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA".
Example 2:
Input: tiles = "AAABBC"
Output: 188
Example 3:
Input: tiles = "V"
Output: 1
Constraints:
1 <= tiles.length <= 7
tiles consists of uppercase English letters.
|
class Solution:
def numTilePossibilities(self, tiles: str) -> int:
res = 0
freqs = [f + 1 for f in Counter(tiles).values()]
for t in itertools.product(*map(range, freqs)):
n = sum(t)
subtotal = math.factorial(n)
for freq in t:
subtotal //= math.factorial(freq)
res += subtotal
return res - 1
|
You have n tiles, where each tile has one letter tiles[i] printed on it.
Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.
Example 1:
Input: tiles = "AAB"
Output: 8
Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA".
Example 2:
Input: tiles = "AAABBC"
Output: 188
Example 3:
Input: tiles = "V"
Output: 1
Constraints:
1 <= tiles.length <= 7
tiles consists of uppercase English letters.
|
class Solution:
def numTilePossibilities(self, tiles: str) -> int:
return len(set(x for i in range(1,len(tiles)+1) for x in itertools.permutations(tiles,i)))
|
You have n tiles, where each tile has one letter tiles[i] printed on it.
Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.
Example 1:
Input: tiles = "AAB"
Output: 8
Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA".
Example 2:
Input: tiles = "AAABBC"
Output: 188
Example 3:
Input: tiles = "V"
Output: 1
Constraints:
1 <= tiles.length <= 7
tiles consists of uppercase English letters.
|
class Solution:
def numTilePossibilities(self, tiles: str) -> int:
def freq(tiles):
d = {}
for c in tiles:
if c in d:
d[c] += 1
else:
d[c] = 1
return d
def build(d, s):
new_d = {}
for key, value in d.items():
if key == s:
new_d[key] = value - 1
else:
new_d[key] = value
return new_d
def generate(options):
sol = []
for key, value in options.items():
if value > 0:
sol.append(key)
fringe = generate(build(options, key))
sol += fringe
sol += [key + f for f in fringe]
return sol
return len(set(generate(freq(tiles))))
|
You have n tiles, where each tile has one letter tiles[i] printed on it.
Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.
Example 1:
Input: tiles = "AAB"
Output: 8
Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA".
Example 2:
Input: tiles = "AAABBC"
Output: 188
Example 3:
Input: tiles = "V"
Output: 1
Constraints:
1 <= tiles.length <= 7
tiles consists of uppercase English letters.
|
class Solution:
def numTilePossibilities(self, tiles: str) -> int:
#self.seen=set()
@lru_cache(None)
def find(s):
if len(s)<=1:
return set([s])
ret=set()
for i in range(len(s)):
head=s[i]
tails=find(s[:i]+s[i+1:])
ret=ret.union(tails)
for tail in tails:
for j in range(len(tail)+1):
temp=tail[:j]+head+tail[j:]
ret.add(temp)
return ret
res=find(tiles)
#print(res)
return len(set(res))
|
You have n tiles, where each tile has one letter tiles[i] printed on it.
Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.
Example 1:
Input: tiles = "AAB"
Output: 8
Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA".
Example 2:
Input: tiles = "AAABBC"
Output: 188
Example 3:
Input: tiles = "V"
Output: 1
Constraints:
1 <= tiles.length <= 7
tiles consists of uppercase English letters.
|
from collections import Counter
class Solution:
def numTilePossibilities(self, tiles: str) -> int:
c_all, visited = Counter(tiles), set()
stack = [(x, Counter([x])) for x in c_all]
while stack:
element, c = stack.pop()
if element not in visited:
stack.extend([(element + x, c + Counter([x])) for x in c_all - c])
visited.add(element)
return len(visited)
|
You have n tiles, where each tile has one letter tiles[i] printed on it.
Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.
Example 1:
Input: tiles = "AAB"
Output: 8
Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA".
Example 2:
Input: tiles = "AAABBC"
Output: 188
Example 3:
Input: tiles = "V"
Output: 1
Constraints:
1 <= tiles.length <= 7
tiles consists of uppercase English letters.
|
class Solution:
def numTilePossibilities(self, tiles: str) -> int:
pos = set()
def choose(s, n, pref=''):
if n == 0:
pos.add(pref)
for i in range(len(s)):
choose(s[:i] + s[i+1:], n-1, pref + s[i])
for i in range(1, len(tiles)+1):
choose(tiles, i)
return len(pos)
|
You have n tiles, where each tile has one letter tiles[i] printed on it.
Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.
Example 1:
Input: tiles = "AAB"
Output: 8
Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA".
Example 2:
Input: tiles = "AAABBC"
Output: 188
Example 3:
Input: tiles = "V"
Output: 1
Constraints:
1 <= tiles.length <= 7
tiles consists of uppercase English letters.
|
class Solution:
def numTilePossibilities(self, tiles: str) -> int:
words = set()
curr = ''
tile_count = {}
for x in tiles:
if x not in tile_count:
tile_count[x] = 0
tile_count[x] += 1
def walk(curr, tiles, words):
#print(tiles, curr)
for tile in tiles:
if tiles[tile] > 0:
temp = curr + tile
#print('Temp', temp)
temp_tiles = tiles.copy()
temp_tiles[tile] -= 1
words.add(temp)
walk(temp, temp_tiles, words)
for tile in tile_count:
walk('', tile_count, words)
return len(words)
|
You have n tiles, where each tile has one letter tiles[i] printed on it.
Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.
Example 1:
Input: tiles = "AAB"
Output: 8
Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA".
Example 2:
Input: tiles = "AAABBC"
Output: 188
Example 3:
Input: tiles = "V"
Output: 1
Constraints:
1 <= tiles.length <= 7
tiles consists of uppercase English letters.
|
class Solution:
def __init__(self):
self.total = 0
self.string = []
self.dict_ = {}
self.arr = []
self.n = 0
def perm(self):
if(self.n==len(self.string)):
#print(string)
self.total+=1
#print(self.total)
for i in range(len(self.arr)):
if(self.arr[i][1]>0):
self.arr[i][1]-=1
self.string.append(self.arr[i][0])
self.perm()
self.string.pop()
self.arr[i][1]+=1
def numTilePossibilities(self, tiles: str) -> int:
for string in tiles:
if string in self.dict_:
self.dict_[string]+=1
else:
self.dict_[string] = 1
for key in self.dict_:
temp = [key,self.dict_[key]]
self.arr.append(temp)
#print(self.arr)
for i in range(1,len(tiles)+1):
self.n = i
#print(self.n)
self.perm()
#self.perm()
return self.total
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.