inputs
stringlengths 50
14k
| targets
stringlengths 4
655k
|
|---|---|
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]).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Your algorithm's runtime complexity must be in the order of O(log n).
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
|
class Solution:
def search(self, nums, target):
if len(nums) <= 3: return nums.index(target) if target in nums else -1
l, r = 0, len(nums) - 1
while l < r:
m = (l + r) // 2
left = nums[l]
mid = nums[m]
right = nums[r]
if left == target:
return l
if mid == target:
return m
if right == target:
return r
elif left < right:
print(('mono:', l, r))
if mid < target:
l = m
r -= 1
else:
r = m
l += 1
else:
print(('not mono:', l, r))
if left < target < mid or mid < left < target or target < mid < left:
r = m
l += 1
else:
l = m
r -= 1
return -1
|
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]).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Your algorithm's runtime complexity must be in the order of O(log n).
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
|
class Solution:
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
low = 0
high = len(nums)-1
while high >= low:
mid = high+low//2
if nums[mid] == target:
return mid
elif nums[mid] > nums[high]:
low = mid+1
else:
print ("comes here")
print (high)
print (mid)
print (low)
high = mid-1
print (high)
return -1
|
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]).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Your algorithm's runtime complexity must be in the order of O(log n).
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
|
class Solution:
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if not nums:
return -1
# [4,5,6,7,0,1,2]
# 0
start, end = 0, len(nums) - 1
while start + 1 < end:
mid = start + (end - start) // 2
if target < nums[end]:
if nums[mid] < target or nums[mid] > nums[end]:
start = mid
elif nums[mid] > target and nums[mid] < nums[end]:
end = mid
else:
return mid
elif target > nums[end]:
if nums[mid] > target or nums[mid] < nums[end]:
end = mid
elif nums[mid] < target and nums[mid] > nums[end]:
start = mid
else:
return mid
else:
return len(nums) - 1
if nums[start] == target:
return start
if nums[end] == target:
return end
return -1
|
In the computer world, use restricted resource you have to generate maximum benefit is what we always want to pursue.
For now, suppose you are a dominator of m 0s and n 1s respectively. On the other hand, there is an array with strings consisting of only 0s and 1s.
Now your task is to find the maximum number of strings that you can form with given m 0s and n 1s. Each 0 and 1 can be used at most once.
Note:
The given numbers of 0s and 1s will both not exceed 100
The size of given string array won't exceed 600.
Example 1:
Input: Array = {"10", "0001", "111001", "1", "0"}, m = 5, n = 3
Output: 4
Explanation: This are totally 4 strings can be formed by the using of 5 0s and 3 1s, which are “10,”0001”,”1”,”0”
Example 2:
Input: Array = {"10", "0", "1"}, m = 1, n = 1
Output: 2
Explanation: You could form "10", but then you'd have nothing left. Better form "0" and "1".
|
class Solution:
def getMax(self, arr, m, n):
res = 0
for e in arr:
if m >= e[0] and n >= e[1]:
res += 1
m -= e[0]
n -= e[1]
return res
def findMaxForm(self, strs, m, n):
"""
:type strs: List[str]
:type m: int
:type n: int
:rtype: int
"""
arr = [(s.count('0'), s.count('1')) for s in strs]
arr1 = sorted(arr, key=lambda s: -min(m - s[0], n - s[1]))
arr2 = sorted(arr, key=lambda s: min(s[0], s[1]))
res = max(self.getMax(arr1, m, n), self.getMax(arr2, m, n))
return res
|
In the computer world, use restricted resource you have to generate maximum benefit is what we always want to pursue.
For now, suppose you are a dominator of m 0s and n 1s respectively. On the other hand, there is an array with strings consisting of only 0s and 1s.
Now your task is to find the maximum number of strings that you can form with given m 0s and n 1s. Each 0 and 1 can be used at most once.
Note:
The given numbers of 0s and 1s will both not exceed 100
The size of given string array won't exceed 600.
Example 1:
Input: Array = {"10", "0001", "111001", "1", "0"}, m = 5, n = 3
Output: 4
Explanation: This are totally 4 strings can be formed by the using of 5 0s and 3 1s, which are “10,”0001”,”1”,”0”
Example 2:
Input: Array = {"10", "0", "1"}, m = 1, n = 1
Output: 2
Explanation: You could form "10", but then you'd have nothing left. Better form "0" and "1".
|
class Solution:
def Greedy(self, counts, zeros, ones) :
num = 0;
for a, b in counts :
if a <= zeros and b <= ones :
zeros -= a
ones -= b
num += 1
return num
def findMaxForm(self, strs, m, n):
"""
:type strs: List[str]
:type m: int
:type n: int
:rtype: int
"""
counts = list(map(lambda x : [x.count('0'), x.count('1')], strs))
return max(self.Greedy(sorted(counts, key = lambda c : min(c[0], c[1])), m, n),
self.Greedy(sorted(counts, key = lambda c : min(m - c[0], n - c[1]), reverse = True), m, n))
|
In the computer world, use restricted resource you have to generate maximum benefit is what we always want to pursue.
For now, suppose you are a dominator of m 0s and n 1s respectively. On the other hand, there is an array with strings consisting of only 0s and 1s.
Now your task is to find the maximum number of strings that you can form with given m 0s and n 1s. Each 0 and 1 can be used at most once.
Note:
The given numbers of 0s and 1s will both not exceed 100
The size of given string array won't exceed 600.
Example 1:
Input: Array = {"10", "0001", "111001", "1", "0"}, m = 5, n = 3
Output: 4
Explanation: This are totally 4 strings can be formed by the using of 5 0s and 3 1s, which are “10,”0001”,”1”,”0”
Example 2:
Input: Array = {"10", "0", "1"}, m = 1, n = 1
Output: 2
Explanation: You could form "10", but then you'd have nothing left. Better form "0" and "1".
|
class Solution:
def findMaxForm(self, strs, m, n):
"""
:type strs: List[str]
:type m: int
:type n: int
:rtype: int
"""
def getMax(arr, m, n):
res = 0
for e in arr:
if m >= e[0] and n >= e[1]:
res += 1
m -= e[0]
n -= e[1]
return res
arr = [(s.count('0'), s.count('1')) for s in strs]
arr1 = sorted(arr, key=lambda s: -min(m - s[0], n - s[1]))
arr2 = sorted(arr, key=lambda s: min(s[0], s[1]))
res = max(getMax(arr1, m, n), getMax(arr2, m, n))
return res
|
In the computer world, use restricted resource you have to generate maximum benefit is what we always want to pursue.
For now, suppose you are a dominator of m 0s and n 1s respectively. On the other hand, there is an array with strings consisting of only 0s and 1s.
Now your task is to find the maximum number of strings that you can form with given m 0s and n 1s. Each 0 and 1 can be used at most once.
Note:
The given numbers of 0s and 1s will both not exceed 100
The size of given string array won't exceed 600.
Example 1:
Input: Array = {"10", "0001", "111001", "1", "0"}, m = 5, n = 3
Output: 4
Explanation: This are totally 4 strings can be formed by the using of 5 0s and 3 1s, which are “10,”0001”,”1”,”0”
Example 2:
Input: Array = {"10", "0", "1"}, m = 1, n = 1
Output: 2
Explanation: You could form "10", but then you'd have nothing left. Better form "0" and "1".
|
class Solution:
def Greedy(self, counts, zeros, ones) :
num = 0;
for a, b in counts :
if a <= zeros and b <= ones :
zeros -= a
ones -= b
num += 1
return num
def findMaxForm(self, strs, m, n):
"""
:type strs: List[str]
:type m: int
:type n: int
:rtype: int
"""
counts = [[s.count('0'), s.count('1')] for s in strs]
res1 = self.Greedy(sorted(counts, key=lambda c: min(c[0], c[1])), m, n)
res2 = self.Greedy(sorted(counts, key=lambda c: min(m - c[0], n - c[1]), reverse=True), m, n)
return max(res1, res2)
|
Given an array of scores that are non-negative integers. Player 1 picks one of the numbers from either end of the array followed by the player 2 and then player 1 and so on. Each time a player picks a number, that number will not be available for the next player. This continues until all the scores have been chosen. The player with the maximum score wins.
Given an array of scores, predict whether player 1 is the winner. You can assume each player plays to maximize his score.
Example 1:
Input: [1, 5, 2]
Output: False
Explanation: Initially, player 1 can choose between 1 and 2. If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). So, final score of player 1 is 1 + 2 = 3, and player 2 is 5. Hence, player 1 will never be the winner and you need to return False.
Example 2:
Input: [1, 5, 233, 7]
Output: True
Explanation: Player 1 first chooses 1. Then player 2 have to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.
Note:
1
Any scores in the given array are non-negative integers and will not exceed 10,000,000.
If the scores of both players are equal, then player 1 is still the winner.
|
class Solution:
def PredictTheWinner(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if not nums: return True
n = len(nums)
if n & 1 == 0: return True
dp = [0] * n
for i in range(n-1, -1, -1):
for j in range(i, n):
if i == j:
dp[i] = nums[i]
else:
dp[j] = max(nums[i] - dp[j], nums[j] - dp[j-1])
return dp[n-1] >= 0
|
Given an array of scores that are non-negative integers. Player 1 picks one of the numbers from either end of the array followed by the player 2 and then player 1 and so on. Each time a player picks a number, that number will not be available for the next player. This continues until all the scores have been chosen. The player with the maximum score wins.
Given an array of scores, predict whether player 1 is the winner. You can assume each player plays to maximize his score.
Example 1:
Input: [1, 5, 2]
Output: False
Explanation: Initially, player 1 can choose between 1 and 2. If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). So, final score of player 1 is 1 + 2 = 3, and player 2 is 5. Hence, player 1 will never be the winner and you need to return False.
Example 2:
Input: [1, 5, 233, 7]
Output: True
Explanation: Player 1 first chooses 1. Then player 2 have to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.
Note:
1
Any scores in the given array are non-negative integers and will not exceed 10,000,000.
If the scores of both players are equal, then player 1 is still the winner.
|
class Solution:
def PredictTheWinner(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
# total = sum(nums)
# memo = {}
# def score(l, r, t):
# if l>r: return 0
# if (l, r) not in memo:
# memo[(l, r)] = t-min(score(l+1, r, t-nums[l]), score(l, r-1, t-nums[r]))
# return memo[(l, r)]
# sc = score(0, len(nums)-1, total)
# return sc>=total-sc
N = len(nums)
dp = [[0]*N for _ in range(N)]
pre_sum = [nums[0]]*(N+1)
pre_sum[-1] = 0
for i in range(1, N):
pre_sum[i] = pre_sum[i-1]+nums[i]
for i in range(N):
dp[i][i] = nums[i]
for l in range(1, N):
for i in range(N-l):
dp[i][i+l] = max(pre_sum[i+l]-pre_sum[i-1]-dp[i+1][i+l], pre_sum[i+l]-pre_sum[i-1]-dp[i][i+l-1])
return dp[0][N-1]*2>=pre_sum[N-1]
|
Given an array of scores that are non-negative integers. Player 1 picks one of the numbers from either end of the array followed by the player 2 and then player 1 and so on. Each time a player picks a number, that number will not be available for the next player. This continues until all the scores have been chosen. The player with the maximum score wins.
Given an array of scores, predict whether player 1 is the winner. You can assume each player plays to maximize his score.
Example 1:
Input: [1, 5, 2]
Output: False
Explanation: Initially, player 1 can choose between 1 and 2. If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). So, final score of player 1 is 1 + 2 = 3, and player 2 is 5. Hence, player 1 will never be the winner and you need to return False.
Example 2:
Input: [1, 5, 233, 7]
Output: True
Explanation: Player 1 first chooses 1. Then player 2 have to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.
Note:
1
Any scores in the given array are non-negative integers and will not exceed 10,000,000.
If the scores of both players are equal, then player 1 is still the winner.
|
class Solution:
def PredictTheWinner(self, nums):
cache = {}
def whose_turn(i, j):
return (len(nums) - (j - i + 1)) % 2 == 0
def traverse(i, j):
if (i, j) in cache:
return cache[(i, j)]
p1_turn = whose_turn(i, j)
if i == j:
return (nums[i], 0) if p1_turn else (0, nums[i])
if i + 1 == j:
winning_move = max(nums[i], nums[j])
losing_move = min(nums[i], nums[j])
cache[(i, j)] = (winning_move, losing_move) if p1_turn else (losing_move, winning_move)
return cache[(i, j)]
p1_left, p2_left = traverse(i + 1, j)
p1_right, p2_right = traverse(i, j - 1)
if p1_turn:
p1_move = max(p1_left + nums[i], p1_right + nums[j])
p2_move = p2_left if p1_left + nums[i] >= p1_right + nums[j] else p2_right
else:
p1_move = p1_left if p2_left + nums[i] >= p2_right + nums[j] else p1_right
p2_move = max(p2_left + nums[i], p2_right + nums[j])
cache[(i, j)] = (p1_move, p2_move)
return cache[(i, j)]
p1_final, p2_final = traverse(0, len(nums) - 1)
return p1_final >= p2_final
|
Given an array of scores that are non-negative integers. Player 1 picks one of the numbers from either end of the array followed by the player 2 and then player 1 and so on. Each time a player picks a number, that number will not be available for the next player. This continues until all the scores have been chosen. The player with the maximum score wins.
Given an array of scores, predict whether player 1 is the winner. You can assume each player plays to maximize his score.
Example 1:
Input: [1, 5, 2]
Output: False
Explanation: Initially, player 1 can choose between 1 and 2. If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). So, final score of player 1 is 1 + 2 = 3, and player 2 is 5. Hence, player 1 will never be the winner and you need to return False.
Example 2:
Input: [1, 5, 233, 7]
Output: True
Explanation: Player 1 first chooses 1. Then player 2 have to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.
Note:
1
Any scores in the given array are non-negative integers and will not exceed 10,000,000.
If the scores of both players are equal, then player 1 is still the winner.
|
class Solution:
def PredictTheWinner(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
memo = [ [0 for _ in range(len(nums))] for _ in range(len(nums))]
self.count=0
def winner( left , right , player):
self.count +=1
#print(self.count)
if left == right:
return player * nums[left]
# p1 selct max from each end
# remove the selected
# p2 selects max from each end
# do above seps until no mor num
# 1 5 2
#print( left, right)
if memo[left][right] != 0 :
print((nums[left:right+1]))
return memo[left][right]
#self.count +=1
a = player * nums[left] + winner( left+1 , right, -player )
#self.count +=1
b = player * nums[right] + winner( left , right -1 , -player)
if player == 1:
res = max(a,b)
else:
res = min(a,b)
memo[left][right] = res
return res
self.count=0
return winner( 0, len(nums) -1 , 1) >=0
|
Given an array of scores that are non-negative integers. Player 1 picks one of the numbers from either end of the array followed by the player 2 and then player 1 and so on. Each time a player picks a number, that number will not be available for the next player. This continues until all the scores have been chosen. The player with the maximum score wins.
Given an array of scores, predict whether player 1 is the winner. You can assume each player plays to maximize his score.
Example 1:
Input: [1, 5, 2]
Output: False
Explanation: Initially, player 1 can choose between 1 and 2. If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). So, final score of player 1 is 1 + 2 = 3, and player 2 is 5. Hence, player 1 will never be the winner and you need to return False.
Example 2:
Input: [1, 5, 233, 7]
Output: True
Explanation: Player 1 first chooses 1. Then player 2 have to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.
Note:
1
Any scores in the given array are non-negative integers and will not exceed 10,000,000.
If the scores of both players are equal, then player 1 is still the winner.
|
class Solution:
def PredictTheWinner(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
n = len(nums)
if n == 0:
return False
dp = [[0]*n for i in range(n)]
for i in range(n):
dp[i][i] = nums[i]
for period in range(1,n):
for i in range(n-period):
j = i+period
dp[i][j] = max(nums[i]-dp[i+1][j], nums[j]-dp[i][j-1])
return dp[0][n-1] >= 0
|
Given an array of scores that are non-negative integers. Player 1 picks one of the numbers from either end of the array followed by the player 2 and then player 1 and so on. Each time a player picks a number, that number will not be available for the next player. This continues until all the scores have been chosen. The player with the maximum score wins.
Given an array of scores, predict whether player 1 is the winner. You can assume each player plays to maximize his score.
Example 1:
Input: [1, 5, 2]
Output: False
Explanation: Initially, player 1 can choose between 1 and 2. If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). So, final score of player 1 is 1 + 2 = 3, and player 2 is 5. Hence, player 1 will never be the winner and you need to return False.
Example 2:
Input: [1, 5, 233, 7]
Output: True
Explanation: Player 1 first chooses 1. Then player 2 have to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.
Note:
1
Any scores in the given array are non-negative integers and will not exceed 10,000,000.
If the scores of both players are equal, then player 1 is still the winner.
|
class Solution:
def PredictTheWinner(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
def helper(nums, start, end, mem):
if start == end:
return nums[start]
if (start, end) not in mem:
mem[(start, end)] = max(nums[start] - helper(nums, start + 1, end, mem), nums[end] - helper(nums, start, end - 1, mem))
return mem[(start, end)]
return helper(nums, 0, len(nums) - 1, {}) >= 0
|
Given an array of scores that are non-negative integers. Player 1 picks one of the numbers from either end of the array followed by the player 2 and then player 1 and so on. Each time a player picks a number, that number will not be available for the next player. This continues until all the scores have been chosen. The player with the maximum score wins.
Given an array of scores, predict whether player 1 is the winner. You can assume each player plays to maximize his score.
Example 1:
Input: [1, 5, 2]
Output: False
Explanation: Initially, player 1 can choose between 1 and 2. If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). So, final score of player 1 is 1 + 2 = 3, and player 2 is 5. Hence, player 1 will never be the winner and you need to return False.
Example 2:
Input: [1, 5, 233, 7]
Output: True
Explanation: Player 1 first chooses 1. Then player 2 have to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.
Note:
1
Any scores in the given array are non-negative integers and will not exceed 10,000,000.
If the scores of both players are equal, then player 1 is still the winner.
|
class Solution:
def PredictTheWinner(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
dic = {}
# tnums = tuple(nums)
# move to the solve function
def solve(nums):
###BUG! IndexError: list index out of range
if len(nums) <=1: return sum(nums)
tnums = tuple(nums)
if tnums in dic:
return dic[tnums]
dic[tnums] = max(nums[0]-solve(nums[1:]),nums[-1]-solve(nums[:-1]))
# TypeError: unsupported operand type(s) for -: 'int' and 'NoneType'
return dic[tnums]
return solve(nums) >= 0
|
Given an array of scores that are non-negative integers. Player 1 picks one of the numbers from either end of the array followed by the player 2 and then player 1 and so on. Each time a player picks a number, that number will not be available for the next player. This continues until all the scores have been chosen. The player with the maximum score wins.
Given an array of scores, predict whether player 1 is the winner. You can assume each player plays to maximize his score.
Example 1:
Input: [1, 5, 2]
Output: False
Explanation: Initially, player 1 can choose between 1 and 2. If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). So, final score of player 1 is 1 + 2 = 3, and player 2 is 5. Hence, player 1 will never be the winner and you need to return False.
Example 2:
Input: [1, 5, 233, 7]
Output: True
Explanation: Player 1 first chooses 1. Then player 2 have to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.
Note:
1
Any scores in the given array are non-negative integers and will not exceed 10,000,000.
If the scores of both players are equal, then player 1 is still the winner.
|
class Solution:
def PredictTheWinner(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
total = sum(nums)
dic = {}
def score(i, j, t):
if i>j:
return 0
if (i, j) in dic:
return dic[(i, j)]
ret = max(t-score(i+1, j, t-nums[i]), t-score(i, j-1, t-nums[j]))
dic[(i, j)] = ret
return ret
l = len(nums)
sc = score(0, l-1, total)
return sc>=total-sc
|
Given an array of scores that are non-negative integers. Player 1 picks one of the numbers from either end of the array followed by the player 2 and then player 1 and so on. Each time a player picks a number, that number will not be available for the next player. This continues until all the scores have been chosen. The player with the maximum score wins.
Given an array of scores, predict whether player 1 is the winner. You can assume each player plays to maximize his score.
Example 1:
Input: [1, 5, 2]
Output: False
Explanation: Initially, player 1 can choose between 1 and 2. If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). So, final score of player 1 is 1 + 2 = 3, and player 2 is 5. Hence, player 1 will never be the winner and you need to return False.
Example 2:
Input: [1, 5, 233, 7]
Output: True
Explanation: Player 1 first chooses 1. Then player 2 have to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.
Note:
1
Any scores in the given array are non-negative integers and will not exceed 10,000,000.
If the scores of both players are equal, then player 1 is still the winner.
|
class Solution:
def PredictTheWinner(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if not nums:
return 0
n=len(nums)
dp=[[0]*n for _ in range(n)]
for i in range(n):
dp[i][i]=nums[i]
for length in range(1,n):
for i in range(n-length):
j=i+length
dp[i][j]=max(nums[i]-dp[i+1][j],nums[j]-dp[i][j-1])
return dp[0][-1]>=0
|
Given an array of scores that are non-negative integers. Player 1 picks one of the numbers from either end of the array followed by the player 2 and then player 1 and so on. Each time a player picks a number, that number will not be available for the next player. This continues until all the scores have been chosen. The player with the maximum score wins.
Given an array of scores, predict whether player 1 is the winner. You can assume each player plays to maximize his score.
Example 1:
Input: [1, 5, 2]
Output: False
Explanation: Initially, player 1 can choose between 1 and 2. If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). So, final score of player 1 is 1 + 2 = 3, and player 2 is 5. Hence, player 1 will never be the winner and you need to return False.
Example 2:
Input: [1, 5, 233, 7]
Output: True
Explanation: Player 1 first chooses 1. Then player 2 have to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.
Note:
1
Any scores in the given array are non-negative integers and will not exceed 10,000,000.
If the scores of both players are equal, then player 1 is still the winner.
|
class Solution:
p1dict = {}
p2dict = {}
def play1(self, nums):
if str(nums) in self.p1dict:
return self.p1dict[str(nums)]
if len(nums) == 1:
return nums[0]
ret = max(self.play2(nums[1:]) + nums[0], self.play2(nums[:-1]) + nums[-1])
self.p1dict[str(nums)] = ret
return ret
def play2(self, nums):
if str(nums) in self.p2dict:
return self.p2dict[str(nums)]
if len(nums) == 1:
return -nums[0]
ret = min(self.play1(nums[1:]) - nums[0], self.play1(nums[:-1]) - nums[-1])
self.p2dict[str(nums)] = ret
return ret
def PredictTheWinner(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
return self.play1(nums) >= 0
|
Given an array of scores that are non-negative integers. Player 1 picks one of the numbers from either end of the array followed by the player 2 and then player 1 and so on. Each time a player picks a number, that number will not be available for the next player. This continues until all the scores have been chosen. The player with the maximum score wins.
Given an array of scores, predict whether player 1 is the winner. You can assume each player plays to maximize his score.
Example 1:
Input: [1, 5, 2]
Output: False
Explanation: Initially, player 1 can choose between 1 and 2. If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). So, final score of player 1 is 1 + 2 = 3, and player 2 is 5. Hence, player 1 will never be the winner and you need to return False.
Example 2:
Input: [1, 5, 233, 7]
Output: True
Explanation: Player 1 first chooses 1. Then player 2 have to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.
Note:
1
Any scores in the given array are non-negative integers and will not exceed 10,000,000.
If the scores of both players are equal, then player 1 is still the winner.
|
class Solution:
def PredictTheWinner(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
_cache = {}
return Solution.Moves(self,nums, 0,len(nums)-1, 1, _cache ) >= 0
def Moves(self, nums, ini ,fin, pl, _cache = {}):
memo = str((ini,fin,pl))
if memo in list(_cache.keys()):
return _cache[memo]
if ini == fin :
if pl == 1:
_cache[memo] = nums[ini]
return _cache[memo]
else:
_cache[memo] = - nums[ini]
return _cache[memo]
else:
if pl == 1:
_cache[memo]= max(Solution.Moves(self, nums, ini+1, fin, 2,_cache) + nums[ini] , Solution.Moves(self, nums, ini, fin-1, 2,_cache) + nums[fin])
return _cache[memo]
if pl == 2:
_cache[memo] = min(Solution.Moves(self, nums, ini+1, fin, 1,_cache) - nums[ini] , Solution.Moves(self, nums, ini, fin-1, 1,_cache) - nums[fin])
return _cache[memo]
|
Given an array of scores that are non-negative integers. Player 1 picks one of the numbers from either end of the array followed by the player 2 and then player 1 and so on. Each time a player picks a number, that number will not be available for the next player. This continues until all the scores have been chosen. The player with the maximum score wins.
Given an array of scores, predict whether player 1 is the winner. You can assume each player plays to maximize his score.
Example 1:
Input: [1, 5, 2]
Output: False
Explanation: Initially, player 1 can choose between 1 and 2. If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). So, final score of player 1 is 1 + 2 = 3, and player 2 is 5. Hence, player 1 will never be the winner and you need to return False.
Example 2:
Input: [1, 5, 233, 7]
Output: True
Explanation: Player 1 first chooses 1. Then player 2 have to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.
Note:
1
Any scores in the given array are non-negative integers and will not exceed 10,000,000.
If the scores of both players are equal, then player 1 is still the winner.
|
class Solution:
def PredictTheWinner(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
l = len(nums)
memo = [[None] * l for _ in range(l)]
def predict(start, end, memo):
if start == end:
return nums[start]
if memo[start][end]:
return memo[start][end]
one = nums[start] - predict(start + 1, end, memo)
two = nums[end] - predict(start, end - 1, memo)
memo[start][end] = max(one, two)
return memo[start][end]
return predict(0, len(nums) - 1, memo) >= 0
|
Given an array of scores that are non-negative integers. Player 1 picks one of the numbers from either end of the array followed by the player 2 and then player 1 and so on. Each time a player picks a number, that number will not be available for the next player. This continues until all the scores have been chosen. The player with the maximum score wins.
Given an array of scores, predict whether player 1 is the winner. You can assume each player plays to maximize his score.
Example 1:
Input: [1, 5, 2]
Output: False
Explanation: Initially, player 1 can choose between 1 and 2. If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). So, final score of player 1 is 1 + 2 = 3, and player 2 is 5. Hence, player 1 will never be the winner and you need to return False.
Example 2:
Input: [1, 5, 233, 7]
Output: True
Explanation: Player 1 first chooses 1. Then player 2 have to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.
Note:
1
Any scores in the given array are non-negative integers and will not exceed 10,000,000.
If the scores of both players are equal, then player 1 is still the winner.
|
class Solution:
def PredictTheWinner(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if not nums: return True
n = len(nums)
if n & 1 == 0: return True
dp = [0] * n
for i in range(n-1, -1, -1):
for j in range(i, n):
if i == j:
dp[i] = nums[i]
else:
dp[j] = max(nums[i] - dp[j], nums[j] - dp[j-1])
return dp[n-1] >= 0
|
Given a list of non negative integers, arrange them such that they form the largest number.
Example 1:
Input: [10,2]
Output: "210"
Example 2:
Input: [3,30,34,5,9]
Output: "9534330"
Note: The result may be very large, so you need to return a string instead of an integer.
|
class Solution:
def largestNumber(self, nums):
"""
:type nums: List[int]
:rtype: str
"""
nums = [str(n) for n in nums]
nums.sort(reverse=True)
for i in range(1, len(nums)):
if len(nums[i-1]) > len(nums[i]):
ran = len(nums[i])
j = i
while j-1 >= 0 and nums[j-1][:ran] == nums[j] and nums[j-1]+nums[j]<=nums[j]+nums[j-1]:
nums[j-1], nums[j] = nums[j], nums[j-1]
j -= 1
return str(int(''.join(nums)))
|
Given a list of non negative integers, arrange them such that they form the largest number.
Example 1:
Input: [10,2]
Output: "210"
Example 2:
Input: [3,30,34,5,9]
Output: "9534330"
Note: The result may be very large, so you need to return a string instead of an integer.
|
class Solution:
class MyNumber:
def __init__(self, v):
self.str_val = str(v)
self.val = [int(x) for x in self.str_val]
self.n = len(self.val)
def __cmp__(self, other):
n1 = self.str_val + other.str_val
n2 = other.str_val + self.str_val
return 0 if n1 == n2 else 1 if n1 > n2 else -1
def largestNumber(self, nums):
"""
:type nums: List[int]
:rtype: str
"""
if all(x == 0 for x in nums):
return '0'
myns = [self.MyNumber(x) for x in nums]
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if myns[j].__cmp__(myns[i]) > 0:
t = myns[i]
myns[i] = myns[j]
myns[j] = t
return "".join([x.str_val for x in myns])
|
Given a list of non negative integers, arrange them such that they form the largest number.
Example 1:
Input: [10,2]
Output: "210"
Example 2:
Input: [3,30,34,5,9]
Output: "9534330"
Note: The result may be very large, so you need to return a string instead of an integer.
|
class Solution:
def largestNumber(self, nums):
"""
:type nums: List[int]
:rtype: str
"""
# maxPos = 0
# maxNum = ''
# maxLen = 0
# maxCut = ''
# res = ''
# while nums:
# for i in range(len(nums)):
# cur = nums[i]
# ori = cur
# while cur % 10 == 0:
# cur = cur // 10
# if str(cur) > maxCut or (str(cur) == maxCut and len(str(ori)) < maxLen):
# maxCut = str(cur)
# maxNum = str(ori)
# maxPos = i
# maxLen = len(maxNum)
# nums.pop(maxPos)
# res += maxNum
# maxPos = 0
# maxNum = ''
# maxLen = 0
# maxCut = ''
# return res
maxPos = 0
maxNum = ''
res = ''
while nums:
for i in range(len(nums)):
cur = nums[i]
if str(cur) + maxNum >= maxNum + str(cur):
maxNum = str(cur)
maxPos = i
nums.pop(maxPos)
res += maxNum
maxPos = 0
maxNum = ''
if res[0] == '0':
return '0'
return res
|
Given a list of non negative integers, arrange them such that they form the largest number.
Example 1:
Input: [10,2]
Output: "210"
Example 2:
Input: [3,30,34,5,9]
Output: "9534330"
Note: The result may be very large, so you need to return a string instead of an integer.
|
class Solution:
def largestNumber(self, nums):
"""
:type nums: List[int]
:rtype: str
"""
## edge case: 981 3,31 331 313
strs = [str(num) for num in nums]
def bigger(str1, str2):
if int(str1+str2) >= int(str2+str1):
return str1
else:
return str2
answer = ""
current = strs
while current:
maximum = current[0]
for i in range(len(current)):
maximum = bigger(maximum, current[i])
answer += maximum
current.remove(maximum)
if answer[0] == "0":
return "0"
return answer
|
Given a list of non negative integers, arrange them such that they form the largest number.
Example 1:
Input: [10,2]
Output: "210"
Example 2:
Input: [3,30,34,5,9]
Output: "9534330"
Note: The result may be very large, so you need to return a string instead of an integer.
|
class Solution:
def largestNumber(self, nums):
"""
:type nums: List[int]
:rtype: str
"""
# case 1 34 vs 34
#case2: 3 vs 34 ; 34 vs 3; 30 vs 3; 3 vs 30
# this works:
# compare the element by ourselves according to the rule of largest number first
if nums is None or len(nums) == 0:
return ''
for i in range(len(nums)-1, -1, -1):
for j in range(len(nums)-1, len(nums)-i-1, -1):
#compare element 1, 2
e1 = str(nums[j-1])
e2 = str(nums[j])
#print ("e1, e2: ", e1, e2, nums)
if e1+e2 < e2+e1:
#swap
t = nums[j]
nums[j] = nums[j-1]
nums[j-1] = t
ans = ''
for n in nums:
if n == 0 and ans == '':
continue
ans += str(n)
#print ("nums: ", nums)
return '0' if len(ans) == 0 else ans
|
Given a list of non negative integers, arrange them such that they form the largest number.
Example 1:
Input: [10,2]
Output: "210"
Example 2:
Input: [3,30,34,5,9]
Output: "9534330"
Note: The result may be very large, so you need to return a string instead of an integer.
|
class Solution:
def largestNumber(self, nums):
"""
:type nums: List[int]
:rtype: str
"""
import functools
# s_nums = []
# maximum_length = 0
# result = ""
# dic = {}
# for i in range(0, len(nums)):
# value = str(num[i])
# maximum_length = max(maximum_length, len(value))
# s_nums.append(value)
# dic[i] = True
# for i in range(0, maximum_length-1):
# temp_max = ""
# temp_max_array = []
# for j in range(0, s_nums-1):
# try:
# a = s_nums[j][i]
# try:
# b = s_nums[j][i+1]
# except:
# if dic[j] != False:
# temp_max_array.append(nums[j])
# dic[j] = False
# dic[j] += 1
# except:
# continue
# print(temp_max_array)
# result += ''.join(sorted(temp_max_array))
# return result
nums_str = []
for each in nums:
nums_str.append(str(each))
result = ''.join(sorted(nums_str, key = functools.cmp_to_key(self.comparator)))
if int(result) == 0:
return '0'
else:
return result
def comparator(self, a, b):
num1 = a + b
num2 = b + a
if num1 > num2:
return -1
elif num2 > num1:
return 1
else:
return 0
|
Given a list of non negative integers, arrange them such that they form the largest number.
Example 1:
Input: [10,2]
Output: "210"
Example 2:
Input: [3,30,34,5,9]
Output: "9534330"
Note: The result may be very large, so you need to return a string instead of an integer.
|
class Solution:
def sorting(self, numstr):
newnumstr = []
#print(numstr)
for i in range(0, len(numstr)):
for j in range(1, len(numstr)-i):
if numstr[j-1] + numstr[j] < numstr[j] + numstr[j-1]:
temp = numstr[j-1]
numstr[j-1] = numstr[j]
numstr[j] = temp
#print(numstr)
def largestNumber(self, nums):
"""
:type nums: List[int]
:rtype: str
"""
matrix = dict()
for num in nums:
numstr = str(num)
if numstr[0] not in matrix:
matrix[numstr[0]] = []
matrix[numstr[0]].append(numstr)
print(matrix)
ret = ""
for i in range(9, -1, -1):
if str(i) in matrix:
prenums = matrix[str(i)]
self.sorting(prenums)
#print(prenums)
ret += "".join(prenums)
#print(ret)
return str(int(ret))
|
Given a list of non negative integers, arrange them such that they form the largest number.
Example 1:
Input: [10,2]
Output: "210"
Example 2:
Input: [3,30,34,5,9]
Output: "9534330"
Note: The result may be very large, so you need to return a string instead of an integer.
|
class Solution:
def largestNumber(self, nums):
"""
:type nums: List[int]
:rtype: str
"""
def lexic_comp(a, b):
ab = str(a) + str(b)
ba = str(b) + str(a)
if ab > ba:
return -1
elif ba > ab:
return 1
return 0
import functools
nums.sort(key=functools.cmp_to_key(lexic_comp))
return str(int(''.join(map(str, nums))))
|
Given a list of non negative integers, arrange them such that they form the largest number.
Example 1:
Input: [10,2]
Output: "210"
Example 2:
Input: [3,30,34,5,9]
Output: "9534330"
Note: The result may be very large, so you need to return a string instead of an integer.
|
class Solution:
def largestNumber(self, nums):
"""
:type nums: List[int]
:rtype: str
"""
s=self.sort(nums)
if s.startswith("0"):
return "0"
else:return s
def sort(self,nums):
if not nums:return ""
else:
pivot=nums[0]
left=[]
right=[]
for i in range(1,len(nums)):
if self.compare(nums[i],pivot):
left.append(nums[i])
else:
right.append(nums[i])
return self.sort(left)+str(pivot)+self.sort(right)
def compare(self,num1,num2):
num1,num2=str(num1),str(num2)
return int(num1+num2)>int(num2+num1)
|
Given a list of non negative integers, arrange them such that they form the largest number.
Example 1:
Input: [10,2]
Output: "210"
Example 2:
Input: [3,30,34,5,9]
Output: "9534330"
Note: The result may be very large, so you need to return a string instead of an integer.
|
class Solution:
def largestNumber(self, nums):
"""
:type nums: List[int]
:rtype: str
"""
def cmp_to_key(mycmp):
'Convert a cmp= function into a key= function'
class K:
def __init__(self, obj, *args):
self.obj = obj
def __lt__(self, other):
return mycmp(self.obj, other.obj) < 0
def __gt__(self, other):
return mycmp(self.obj, other.obj) > 0
def __eq__(self, other):
return mycmp(self.obj, other.obj) == 0
def __le__(self, other):
return mycmp(self.obj, other.obj) <= 0
def __ge__(self, other):
return mycmp(self.obj, other.obj) >= 0
def __ne__(self, other):
return mycmp(self.obj, other.obj) != 0
return K
def compare(n1, n2):
#print(n1, n2, ":")
l1 = len(n1)
l2 = len(n2)
i = 0
if l1 != l2:
tmp = n1
n1 = n1 + n2
n2 = n2 + tmp
l1 = l1 + l2
#print(n1, n2)
while i < max(l1, l2):
#print(i, n1[i], n2[i])
if n1[i] < n2[i]:
#print(n1, "<", n2)
return -1
elif n1[i] > n2[i]:
#print(n1, ">", n2)
return 1
i += 1
#print(n1, "=", n2)
return 0
def convert(num):
if num == 0:
return [0]
res = []
while num:
res.append(num % 10)
num //= 10
res.reverse()
return res
nums = list(map(convert, nums))
nums.sort(key=cmp_to_key(compare), reverse=True)
print(nums)
res = [str(c) for num in nums for c in num]
res = "".join(res).lstrip('0')
if not res:
res = '0'
return res
|
Given a list of non negative integers, arrange them such that they form the largest number.
Example 1:
Input: [10,2]
Output: "210"
Example 2:
Input: [3,30,34,5,9]
Output: "9534330"
Note: The result may be very large, so you need to return a string instead of an integer.
|
class Solution:
def largestNumber(self, nums):
"""
:type nums: List[int]
:rtype: str
"""
s=self.sort(nums)
if s.startswith("0"):
return "0"
else:return s
def sort(self,nums):
if not nums:return ""
else:
pivot=nums[0]
left=[]
right=[]
for i in range(1,len(nums)):
if self.compare(nums[i],pivot):
left.append(nums[i])
else:
right.append(nums[i])
return self.sort(left)+str(pivot)+self.sort(right)
def compare(self,num1,num2):
return int(str(num1)+str(num2))>int(str(num2)+str(num1))
|
In the world of Dota2, there are two parties: the Radiant and the Dire.
The Dota2 senate consists of senators coming from two parties. Now the senate wants to make a decision about a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise one of the two rights:
Ban one senator's right: A senator can make another senator lose all his rights in this and all the following rounds.
Announce the victory: If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and make the decision about the change in the game.
Given a string representing each senator's party belonging. The character 'R' and 'D' represent the Radiant party and the Dire party respectively. Then if there are n senators, the size of the given string will be n.
The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure.
Suppose every senator is smart enough and will play the best strategy for his own party, you need to predict which party will finally announce the victory and make the change in the Dota2 game. The output should be Radiant or Dire.
Example 1:
Input: "RD"
Output: "Radiant"
Explanation: The first senator comes from Radiant and he can just ban the next senator's right in the round 1. And the second senator can't exercise any rights any more since his right has been banned. And in the round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote.
Example 2:
Input: "RDD"
Output: "Dire"
Explanation:
The first senator comes from Radiant and he can just ban the next senator's right in the round 1. And the second senator can't exercise any rights anymore since his right has been banned. And the third senator comes from Dire and he can ban the first senator's right in the round 1. And in the round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote.
Note:
The length of the given string will in the range [1, 10,000].
|
class Solution:
def predictPartyVictory(self, senate):
"""
:type senate: str
:rtype: str
"""
num = 0 # num of Reeding R
while ('R' in senate and 'D' in senate):
res = []
for i in senate:
if i=='R':
if num>=0:
res.append(i)
num+=1
else:
if num<=0:
res.append(i)
num-=1
senate = res
return 'Radiant' if 'R' in senate else 'Dire'
|
In the world of Dota2, there are two parties: the Radiant and the Dire.
The Dota2 senate consists of senators coming from two parties. Now the senate wants to make a decision about a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise one of the two rights:
Ban one senator's right: A senator can make another senator lose all his rights in this and all the following rounds.
Announce the victory: If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and make the decision about the change in the game.
Given a string representing each senator's party belonging. The character 'R' and 'D' represent the Radiant party and the Dire party respectively. Then if there are n senators, the size of the given string will be n.
The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure.
Suppose every senator is smart enough and will play the best strategy for his own party, you need to predict which party will finally announce the victory and make the change in the Dota2 game. The output should be Radiant or Dire.
Example 1:
Input: "RD"
Output: "Radiant"
Explanation: The first senator comes from Radiant and he can just ban the next senator's right in the round 1. And the second senator can't exercise any rights any more since his right has been banned. And in the round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote.
Example 2:
Input: "RDD"
Output: "Dire"
Explanation:
The first senator comes from Radiant and he can just ban the next senator's right in the round 1. And the second senator can't exercise any rights anymore since his right has been banned. And the third senator comes from Dire and he can ban the first senator's right in the round 1. And in the round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote.
Note:
The length of the given string will in the range [1, 10,000].
|
class Solution:
def predictPartyVictory(self, senate):
"""
:type senate: str
:rtype: str
"""
from collections import deque
n = len(senate)
queueR = deque()
queueD = deque()
for i in range(len(senate)):
if senate[i] == "R":
queueR.append(i)
else:
queueD.append(i)
while queueR and queueD:
p1 = queueR.popleft()
p2 = queueD.popleft()
if p1 < p2:
queueR.append(p1+n)
else:
queueD.append(p2+n)
if queueR:
return "Radiant"
return "Dire"
|
In the world of Dota2, there are two parties: the Radiant and the Dire.
The Dota2 senate consists of senators coming from two parties. Now the senate wants to make a decision about a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise one of the two rights:
Ban one senator's right: A senator can make another senator lose all his rights in this and all the following rounds.
Announce the victory: If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and make the decision about the change in the game.
Given a string representing each senator's party belonging. The character 'R' and 'D' represent the Radiant party and the Dire party respectively. Then if there are n senators, the size of the given string will be n.
The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure.
Suppose every senator is smart enough and will play the best strategy for his own party, you need to predict which party will finally announce the victory and make the change in the Dota2 game. The output should be Radiant or Dire.
Example 1:
Input: "RD"
Output: "Radiant"
Explanation: The first senator comes from Radiant and he can just ban the next senator's right in the round 1. And the second senator can't exercise any rights any more since his right has been banned. And in the round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote.
Example 2:
Input: "RDD"
Output: "Dire"
Explanation:
The first senator comes from Radiant and he can just ban the next senator's right in the round 1. And the second senator can't exercise any rights anymore since his right has been banned. And the third senator comes from Dire and he can ban the first senator's right in the round 1. And in the round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote.
Note:
The length of the given string will in the range [1, 10,000].
|
class Solution:
def predictPartyVictory(self, senate):
"""
:type senate: str
:rtype: str
"""
r = collections.deque()
d = collections.deque()
for i,c in enumerate(senate):
if c == "R":
r.append(i)
else:
d.append(i)
return self.eliminateSenators(r,d)
def eliminateSenators(self,r,d):
if len(r)==0: return "Dire"
if len(d)==0:return "Radiant"
r2 = collections.deque()
d2 = collections.deque()
while len(r)> 0 or len(d)>0:
if len(r)==0:
if len(r2)==0:
return "Dire"
else:
r2.popleft()
d2.append(d.popleft())
elif len(d)==0:
if len(d2)==0:
return "Radiant"
else:
d2.popleft()
r2.append(r.popleft())
else:
r_curr = r.popleft()
d_curr = d.popleft()
if r_curr < d_curr:
r2.append(r_curr)
else:
d2.append(d_curr)
return self.eliminateSenators(r2,d2)
|
In the world of Dota2, there are two parties: the Radiant and the Dire.
The Dota2 senate consists of senators coming from two parties. Now the senate wants to make a decision about a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise one of the two rights:
Ban one senator's right: A senator can make another senator lose all his rights in this and all the following rounds.
Announce the victory: If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and make the decision about the change in the game.
Given a string representing each senator's party belonging. The character 'R' and 'D' represent the Radiant party and the Dire party respectively. Then if there are n senators, the size of the given string will be n.
The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure.
Suppose every senator is smart enough and will play the best strategy for his own party, you need to predict which party will finally announce the victory and make the change in the Dota2 game. The output should be Radiant or Dire.
Example 1:
Input: "RD"
Output: "Radiant"
Explanation: The first senator comes from Radiant and he can just ban the next senator's right in the round 1. And the second senator can't exercise any rights any more since his right has been banned. And in the round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote.
Example 2:
Input: "RDD"
Output: "Dire"
Explanation:
The first senator comes from Radiant and he can just ban the next senator's right in the round 1. And the second senator can't exercise any rights anymore since his right has been banned. And the third senator comes from Dire and he can ban the first senator's right in the round 1. And in the round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote.
Note:
The length of the given string will in the range [1, 10,000].
|
class Solution:
def predictPartyVictory(self, senate):
"""
:type senate: str
:rtype: str
"""
queue = collections.deque()
people, bans = [0, 0], [0, 0]
for person in senate:
x = person == 'R'
people[x] += 1
queue.append(x)
while all(people):
x = queue.popleft()
if bans[x]:
bans[x] -= 1
people[x] -= 1
else:
bans[x^1] += 1
queue.append(x)
return 'Radiant' if people[1] else 'Dire'
|
In the world of Dota2, there are two parties: the Radiant and the Dire.
The Dota2 senate consists of senators coming from two parties. Now the senate wants to make a decision about a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise one of the two rights:
Ban one senator's right: A senator can make another senator lose all his rights in this and all the following rounds.
Announce the victory: If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and make the decision about the change in the game.
Given a string representing each senator's party belonging. The character 'R' and 'D' represent the Radiant party and the Dire party respectively. Then if there are n senators, the size of the given string will be n.
The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure.
Suppose every senator is smart enough and will play the best strategy for his own party, you need to predict which party will finally announce the victory and make the change in the Dota2 game. The output should be Radiant or Dire.
Example 1:
Input: "RD"
Output: "Radiant"
Explanation: The first senator comes from Radiant and he can just ban the next senator's right in the round 1. And the second senator can't exercise any rights any more since his right has been banned. And in the round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote.
Example 2:
Input: "RDD"
Output: "Dire"
Explanation:
The first senator comes from Radiant and he can just ban the next senator's right in the round 1. And the second senator can't exercise any rights anymore since his right has been banned. And the third senator comes from Dire and he can ban the first senator's right in the round 1. And in the round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote.
Note:
The length of the given string will in the range [1, 10,000].
|
class Solution:
def predictPartyVictory(self, senate):
"""
:type senate: str
:rtype: str
"""
queue = collections.deque()
people, bans = [0, 0], [0, 0]
for person in senate:
x = person == 'R'
people[x] += 1
queue.append(x)
while all(people):
x = queue.popleft()
if bans[x]:
bans[x] -= 1
people[x] -= 1
else:
bans[x^1] += 1
queue.append(x)
return "Radiant" if people[1] else "Dire"
|
In the world of Dota2, there are two parties: the Radiant and the Dire.
The Dota2 senate consists of senators coming from two parties. Now the senate wants to make a decision about a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise one of the two rights:
Ban one senator's right: A senator can make another senator lose all his rights in this and all the following rounds.
Announce the victory: If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and make the decision about the change in the game.
Given a string representing each senator's party belonging. The character 'R' and 'D' represent the Radiant party and the Dire party respectively. Then if there are n senators, the size of the given string will be n.
The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure.
Suppose every senator is smart enough and will play the best strategy for his own party, you need to predict which party will finally announce the victory and make the change in the Dota2 game. The output should be Radiant or Dire.
Example 1:
Input: "RD"
Output: "Radiant"
Explanation: The first senator comes from Radiant and he can just ban the next senator's right in the round 1. And the second senator can't exercise any rights any more since his right has been banned. And in the round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote.
Example 2:
Input: "RDD"
Output: "Dire"
Explanation:
The first senator comes from Radiant and he can just ban the next senator's right in the round 1. And the second senator can't exercise any rights anymore since his right has been banned. And the third senator comes from Dire and he can ban the first senator's right in the round 1. And in the round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote.
Note:
The length of the given string will in the range [1, 10,000].
|
class Solution:
def predictPartyVictory(self, senate):
"""
:type senate: str
:rtype: str
"""
s = [1 if x == 'R' else 0 for x in senate]
Rban = 0
Dban = 0
i = 0
ban = False
while True:
if s[i] == -1: pass
else:
if s[i] == 1:
if Dban > 0:
Dban -= 1
s[i] = -1
ban = True
else: Rban += 1
else:
if Rban > 0:
Rban -= 1
s[i] = -1
ban = True
else: Dban += 1
i += 1
if i == len(s):
i = 0
if not ban: break
else: ban = False
if Rban > 0: return "Radiant"
else: return "Dire"
|
There are N piles of stones arranged in a row. The i-th pile has stones[i] stones.
A move consists of merging exactly K consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these K piles.
Find the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1.
Example 1:
Input: stones = [3,2,4,1], K = 2
Output: 20
Explanation:
We start with [3, 2, 4, 1].
We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].
We merge [4, 1] for a cost of 5, and we are left with [5, 5].
We merge [5, 5] for a cost of 10, and we are left with [10].
The total cost was 20, and this is the minimum possible.
Example 2:
Input: stones = [3,2,4,1], K = 3
Output: -1
Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
Example 3:
Input: stones = [3,5,1,2,6], K = 3
Output: 25
Explanation:
We start with [3, 5, 1, 2, 6].
We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].
We merge [3, 8, 6] for a cost of 17, and we are left with [17].
The total cost was 25, and this is the minimum possible.
Note:
1 <= stones.length <= 30
2 <= K <= 30
1 <= stones[i] <= 100
|
class Solution:
def mergeStones(self, stones: List[int], K: int) -> int:
n = len(stones)
if (n - 1) % (K - 1) != 0:
return -1
prefix = [0]
for s in stones:
prefix.append(prefix[-1] + s)
@lru_cache(None)
def dp(i, j):
if j - i + 1 < K:
return 0
res = 0
if (j - i) % (K - 1) == 0:
res = prefix[j+1] - prefix[i]
return res + min(dp(i, mid) + dp(mid+1, j) for mid in range(i, j, K - 1))
return dp(0, n - 1)
|
There are N piles of stones arranged in a row. The i-th pile has stones[i] stones.
A move consists of merging exactly K consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these K piles.
Find the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1.
Example 1:
Input: stones = [3,2,4,1], K = 2
Output: 20
Explanation:
We start with [3, 2, 4, 1].
We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].
We merge [4, 1] for a cost of 5, and we are left with [5, 5].
We merge [5, 5] for a cost of 10, and we are left with [10].
The total cost was 20, and this is the minimum possible.
Example 2:
Input: stones = [3,2,4,1], K = 3
Output: -1
Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
Example 3:
Input: stones = [3,5,1,2,6], K = 3
Output: 25
Explanation:
We start with [3, 5, 1, 2, 6].
We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].
We merge [3, 8, 6] for a cost of 17, and we are left with [17].
The total cost was 25, and this is the minimum possible.
Note:
1 <= stones.length <= 30
2 <= K <= 30
1 <= stones[i] <= 100
|
class Solution:
def mergeStones(self, stones: List[int], K: int) -> int:
n = len(stones)
if (n-1)%(K-1) != 0:
return -1
dp = [[0]*n for _ in range(n)]
sums = [0]*(n+1)
for i in range(1,n+1):
sums[i] = sums[i-1]+stones[i-1]
for length in range(K,n+1):
for i in range(n-length+1):
j = i+length-1
dp[i][j] = float('inf')
for t in range(i,j,K-1):
dp[i][j] = min(dp[i][j], dp[i][t]+dp[t+1][j])
if (j-i)%(K-1)==0:
dp[i][j] += sums[j+1]-sums[i]
return dp[0][n-1]
|
There are N piles of stones arranged in a row. The i-th pile has stones[i] stones.
A move consists of merging exactly K consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these K piles.
Find the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1.
Example 1:
Input: stones = [3,2,4,1], K = 2
Output: 20
Explanation:
We start with [3, 2, 4, 1].
We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].
We merge [4, 1] for a cost of 5, and we are left with [5, 5].
We merge [5, 5] for a cost of 10, and we are left with [10].
The total cost was 20, and this is the minimum possible.
Example 2:
Input: stones = [3,2,4,1], K = 3
Output: -1
Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
Example 3:
Input: stones = [3,5,1,2,6], K = 3
Output: 25
Explanation:
We start with [3, 5, 1, 2, 6].
We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].
We merge [3, 8, 6] for a cost of 17, and we are left with [17].
The total cost was 25, and this is the minimum possible.
Note:
1 <= stones.length <= 30
2 <= K <= 30
1 <= stones[i] <= 100
|
class Solution:
def mergeStones(self, stones: List[int], K: int) -> int:
@lru_cache(None)
def recursive(i, j, piles):
if j - i + 1 < K: return 0
if piles == 1:
return recursive(i, j, K) + pre_sum[j+1] - pre_sum[i]
else:
min_cost = float('inf')
for k in range(i, j, K - 1):
min_cost = min(min_cost, recursive(i, k, 1) + recursive(k + 1, j, piles - 1))
return min_cost
n = len(stones)
if (n - 1) % (K - 1) != 0:
return -1
pre_sum = [0] * (n + 1)
for i in range(n):
pre_sum[i + 1] = pre_sum[i] + stones[i]
return recursive(0, n - 1, 1)
|
There are N piles of stones arranged in a row. The i-th pile has stones[i] stones.
A move consists of merging exactly K consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these K piles.
Find the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1.
Example 1:
Input: stones = [3,2,4,1], K = 2
Output: 20
Explanation:
We start with [3, 2, 4, 1].
We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].
We merge [4, 1] for a cost of 5, and we are left with [5, 5].
We merge [5, 5] for a cost of 10, and we are left with [10].
The total cost was 20, and this is the minimum possible.
Example 2:
Input: stones = [3,2,4,1], K = 3
Output: -1
Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
Example 3:
Input: stones = [3,5,1,2,6], K = 3
Output: 25
Explanation:
We start with [3, 5, 1, 2, 6].
We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].
We merge [3, 8, 6] for a cost of 17, and we are left with [17].
The total cost was 25, and this is the minimum possible.
Note:
1 <= stones.length <= 30
2 <= K <= 30
1 <= stones[i] <= 100
|
class Solution:
def mergeStones(self, stones: List[int], K: int) -> int:
n = len(stones)
k = K
if (n < k and n != 1) or (n - 1) % (k - 1) != 0:
return -1
if n == 1:
return 0
dp = [[-1 for _ in range(n)] for _ in range(n)] # dp[i][j] stores min cost to reduce [i, j] as much as possible
self.solve(stones, 0, n - 1, k, dp)
# print(dp)
return dp[0][n - 1]
def solve(self, stones, l, r, k, dp):
length = r - l + 1
if length < k:
dp[l][r] = 0
return
if length == k:
dp[l][r] = sum(stones[l:r+1])
return
res = float('inf')
for m in range(l, r):
length = length
length_l = m - l + 1
length_r = r - m
rem = k - 1 if length % (k - 1) == 0 else length % (k - 1)
rem_l = k - 1 if length_l % (k - 1) == 0 else length_l % (k - 1)
rem_r = k - 1 if length_r % (k - 1) == 0 else length_r % (k - 1)
rem_total = k - 1 if (rem_l + rem_r) % (k - 1) == 0 else (rem_l + rem_r) % (k - 1)
if rem_total == rem and (rem_l + rem_r) <= k:
if dp[l][m] == -1:
self.solve(stones, l, m, k, dp)
if dp[m + 1][r] == -1:
self.solve(stones, m + 1, r, k, dp)
# print('lets check {} to {} and {}'.format(l, m, r))
# print(dp[l][m], dp[m+1][r])
res = min(res, dp[l][m] + dp[m+1][r])
dp[l][r] = res
if rem == 1:
dp[l][r] += sum(stones[l:r+1])
# class Solution:
# def mergeStones(self, stones: List[int], K: int) -> int:
# n = len(stones)
# k = K
# if (n < k and n != 1) or (n - k) % (k - 1) != 0:
# return -1
# if n == 1:
# return 0
# return self.comp_min(stones, k, -1)
# def comp_min(self, stones, k, locked): # can't do a merge which only involves the first 'locked' stones
# n = len(stones)
# if n == k:
# return sum(stones)
# total_cur_cost = float('inf')
# for i in range(max(0, locked - k + 2), n - k + 1):
# cur_cost = sum(stones[i:i+k])
# new_stones = stones[:i] + [cur_cost] + stones[i+k:]
# new_locked = i - 1
# tmp = self.comp_min(new_stones, k, new_locked)
# total_cur_cost = min(total_cur_cost, cur_cost + tmp)
# return total_cur_cost
|
There are N piles of stones arranged in a row. The i-th pile has stones[i] stones.
A move consists of merging exactly K consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these K piles.
Find the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1.
Example 1:
Input: stones = [3,2,4,1], K = 2
Output: 20
Explanation:
We start with [3, 2, 4, 1].
We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].
We merge [4, 1] for a cost of 5, and we are left with [5, 5].
We merge [5, 5] for a cost of 10, and we are left with [10].
The total cost was 20, and this is the minimum possible.
Example 2:
Input: stones = [3,2,4,1], K = 3
Output: -1
Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
Example 3:
Input: stones = [3,5,1,2,6], K = 3
Output: 25
Explanation:
We start with [3, 5, 1, 2, 6].
We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].
We merge [3, 8, 6] for a cost of 17, and we are left with [17].
The total cost was 25, and this is the minimum possible.
Note:
1 <= stones.length <= 30
2 <= K <= 30
1 <= stones[i] <= 100
|
from functools import lru_cache
import itertools
class Solution:
def mergeStones(self, stones: List[int], K: int) -> int:
# dp[i][j] means the minimum cost needed to merge stones[i] ~ stones[j].
# Time complexity: O(N^3 / K)
# Space complexity: O(KN^2)
n = len(stones)
if (n - 1) % (K - 1): return -1
prefix = [0] * (n + 1)
for i in range(n):
prefix[i + 1] = prefix[i] + stones[i]
@lru_cache(None)
def dp(i, j):
if j - i + 1 < K: return 0
res = min(dp(i, mid) + dp(mid + 1, j) for mid in range(i, j, K - 1))
if (j - i) % (K - 1) == 0:
res += prefix[j + 1] - prefix[i]
return res
return dp(0, n - 1)
|
There are N piles of stones arranged in a row. The i-th pile has stones[i] stones.
A move consists of merging exactly K consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these K piles.
Find the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1.
Example 1:
Input: stones = [3,2,4,1], K = 2
Output: 20
Explanation:
We start with [3, 2, 4, 1].
We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].
We merge [4, 1] for a cost of 5, and we are left with [5, 5].
We merge [5, 5] for a cost of 10, and we are left with [10].
The total cost was 20, and this is the minimum possible.
Example 2:
Input: stones = [3,2,4,1], K = 3
Output: -1
Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
Example 3:
Input: stones = [3,5,1,2,6], K = 3
Output: 25
Explanation:
We start with [3, 5, 1, 2, 6].
We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].
We merge [3, 8, 6] for a cost of 17, and we are left with [17].
The total cost was 25, and this is the minimum possible.
Note:
1 <= stones.length <= 30
2 <= K <= 30
1 <= stones[i] <= 100
|
from functools import lru_cache
import itertools
class Solution:
def mergeStones(self, stones: List[int], K: int) -> int:
# Time complexity: O(N^3 / K)
# Space complexity: O(KN^2)
n = len(stones)
if (n - 1) % (K - 1): return -1
prefix = [0] * (n + 1)
for i in range(n):
prefix[i + 1] = prefix[i] + stones[i]
@lru_cache(None)
def dp(i, j):
if j - i + 1 < K: return 0
res = min(dp(i, mid) + dp(mid + 1, j) for mid in range(i, j, K - 1))
if (j - i) % (K - 1) == 0:
res += prefix[j + 1] - prefix[i]
return res
return dp(0, n - 1)
|
There are N piles of stones arranged in a row. The i-th pile has stones[i] stones.
A move consists of merging exactly K consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these K piles.
Find the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1.
Example 1:
Input: stones = [3,2,4,1], K = 2
Output: 20
Explanation:
We start with [3, 2, 4, 1].
We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].
We merge [4, 1] for a cost of 5, and we are left with [5, 5].
We merge [5, 5] for a cost of 10, and we are left with [10].
The total cost was 20, and this is the minimum possible.
Example 2:
Input: stones = [3,2,4,1], K = 3
Output: -1
Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
Example 3:
Input: stones = [3,5,1,2,6], K = 3
Output: 25
Explanation:
We start with [3, 5, 1, 2, 6].
We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].
We merge [3, 8, 6] for a cost of 17, and we are left with [17].
The total cost was 25, and this is the minimum possible.
Note:
1 <= stones.length <= 30
2 <= K <= 30
1 <= stones[i] <= 100
|
class Solution:
def mergeStones(self, stones: List[int], K: int) -> int:
dp, N, Sum, H = {}, len(stones), {-1: 0}, {}
for i in range(N):
j, dp[i], H[i], Sum[i] = i, {}, {}, Sum[i - 1] + stones[i]
while j > -1:
H[i][j] = (i-j+1)%(K-1)+(K-1)*(1//(1+(i-j+1)%(K-1)))
if i - j < K - 1: dp[i][j] = 0
else:
dp[i][j] = dp[i][i] + dp[i - 1][j]
for k in range(j + 1, i + 1):
if H[i][k] + H[k - 1][j] == H[i][j] or H[i][k] + H[k - 1][j] == K:
dp[i][j] = min(dp[i][j], dp[i][k] + dp[k - 1][j])
if H[i][j] == 1: dp[i][j] += Sum[i] - Sum[j - 1]
j = j - 1
return dp[N-1][0]*(1//H[N-1][0]) - min(H[N-1][0]-1, 1)
|
There are N piles of stones arranged in a row. The i-th pile has stones[i] stones.
A move consists of merging exactly K consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these K piles.
Find the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1.
Example 1:
Input: stones = [3,2,4,1], K = 2
Output: 20
Explanation:
We start with [3, 2, 4, 1].
We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].
We merge [4, 1] for a cost of 5, and we are left with [5, 5].
We merge [5, 5] for a cost of 10, and we are left with [10].
The total cost was 20, and this is the minimum possible.
Example 2:
Input: stones = [3,2,4,1], K = 3
Output: -1
Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
Example 3:
Input: stones = [3,5,1,2,6], K = 3
Output: 25
Explanation:
We start with [3, 5, 1, 2, 6].
We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].
We merge [3, 8, 6] for a cost of 17, and we are left with [17].
The total cost was 25, and this is the minimum possible.
Note:
1 <= stones.length <= 30
2 <= K <= 30
1 <= stones[i] <= 100
|
class Solution:
def mergeStones(self, stones: List[int], K: int) -> int:
n = len(stones)
k = K
if (n < k and n != 1) or (n - 1) % (k - 1) != 0:
return -1
if n == 1:
return 0
dp = [[-1 for _ in range(n)] for _ in range(n)] # dp[i][j] stores min cost to reduce [i, j] as much as possible
self.solve(stones, 0, n - 1, k, dp)
return dp[0][n - 1]
def solve(self, stones, l, r, k, dp):
length = r - l + 1
if length < k:
dp[l][r] = 0
return
if length == k:
dp[l][r] = sum(stones[l:r+1])
return
res = float('inf')
for m in range(l, r):
length = length
length_l = m - l + 1
length_r = r - m
rem = k - 1 if length % (k - 1) == 0 else length % (k - 1)
rem_l = k - 1 if length_l % (k - 1) == 0 else length_l % (k - 1)
rem_r = k - 1 if length_r % (k - 1) == 0 else length_r % (k - 1)
rem_total = k - 1 if (rem_l + rem_r) % (k - 1) == 0 else (rem_l + rem_r) % (k - 1)
if rem_total == rem and (rem_l + rem_r) <= k:
if dp[l][m] == -1:
self.solve(stones, l, m, k, dp)
if dp[m + 1][r] == -1:
self.solve(stones, m + 1, r, k, dp)
res = min(res, dp[l][m] + dp[m+1][r])
dp[l][r] = res
if rem == 1:
dp[l][r] += sum(stones[l:r+1])
|
There are N piles of stones arranged in a row. The i-th pile has stones[i] stones.
A move consists of merging exactly K consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these K piles.
Find the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1.
Example 1:
Input: stones = [3,2,4,1], K = 2
Output: 20
Explanation:
We start with [3, 2, 4, 1].
We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].
We merge [4, 1] for a cost of 5, and we are left with [5, 5].
We merge [5, 5] for a cost of 10, and we are left with [10].
The total cost was 20, and this is the minimum possible.
Example 2:
Input: stones = [3,2,4,1], K = 3
Output: -1
Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
Example 3:
Input: stones = [3,5,1,2,6], K = 3
Output: 25
Explanation:
We start with [3, 5, 1, 2, 6].
We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].
We merge [3, 8, 6] for a cost of 17, and we are left with [17].
The total cost was 25, and this is the minimum possible.
Note:
1 <= stones.length <= 30
2 <= K <= 30
1 <= stones[i] <= 100
|
class Solution:
def mergeStones(self, stones: List[int], K: int) -> int:
total = len(stones)
if (total-1) % (K-1):
return -1
prefix = [0] * (total+1)
for i in range(total):
prefix[i+1] = prefix[i]+stones[i]
import functools
@functools.lru_cache(None)
def dfs(i, j):
if j-i+1 < K:
return 0
res = min(dfs(i,k)+dfs(k+1,j) for k in range(i, j, K-1))
if (j-i) % (K-1) == 0:
res += prefix[j+1]-prefix[i]
return res
return dfs(0, total-1)
|
There are N piles of stones arranged in a row. The i-th pile has stones[i] stones.
A move consists of merging exactly K consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these K piles.
Find the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1.
Example 1:
Input: stones = [3,2,4,1], K = 2
Output: 20
Explanation:
We start with [3, 2, 4, 1].
We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].
We merge [4, 1] for a cost of 5, and we are left with [5, 5].
We merge [5, 5] for a cost of 10, and we are left with [10].
The total cost was 20, and this is the minimum possible.
Example 2:
Input: stones = [3,2,4,1], K = 3
Output: -1
Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
Example 3:
Input: stones = [3,5,1,2,6], K = 3
Output: 25
Explanation:
We start with [3, 5, 1, 2, 6].
We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].
We merge [3, 8, 6] for a cost of 17, and we are left with [17].
The total cost was 25, and this is the minimum possible.
Note:
1 <= stones.length <= 30
2 <= K <= 30
1 <= stones[i] <= 100
|
class Solution:
def mergeStones(self, stones: List[int], K: int) -> int:
'''
dp[i][j][k]: the min cost to merge stone[i: j + 1] into k piles
the range for consecutive piles of stone[i:j + 1] to be k piles after merging can be divided into two parts (for stones[:n] be finally merged into 1 pile):
1. a sub-range from the start to the devide that is sured to be merged in to 1 pile: dp[i][divide][1]
divide goes from start by K - 1 step to make this happen: dp[i][divide][1] < math.inf
2. a sub-range from the divide + 1 to the end (not guaranteed to be realistic): dp[divide + 1][k - 1]
The longer ranges are always merged from the smaller ones, no matter how the smaller ones were merged from. That is why this is a DP problem.
'''
n = len(stones)
if K > 2 and n % (K - 1) != 1:
return -1
dp = [[[math.inf] * (K + 1) for i in range(n)] for j in range(n)]
for i in range(n):
dp[i][i][1] = 0
presum = [stones[0]]
for i in range(1, n):
presum.append(presum[i - 1] + stones[i])
def stones_in_range(i, j):
return presum[j] - presum[i - 1] if i > 0 else presum[j]
for rangelen in range(2, n + 1):
for start in range(n + 1 - rangelen):
end = start + rangelen - 1
for k in range(2, K + 1):
for divide in range(start, end, K - 1):
dp[start][end][k] = min(dp[start][end][k], dp[start][divide][1] + dp[divide + 1][end][k - 1])
if dp[start][end][K] < math.inf:
dp[start][end][1] = dp[start][end][K] + stones_in_range(start, end)
return dp[0][n - 1][1]
|
There are N piles of stones arranged in a row. The i-th pile has stones[i] stones.
A move consists of merging exactly K consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these K piles.
Find the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1.
Example 1:
Input: stones = [3,2,4,1], K = 2
Output: 20
Explanation:
We start with [3, 2, 4, 1].
We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].
We merge [4, 1] for a cost of 5, and we are left with [5, 5].
We merge [5, 5] for a cost of 10, and we are left with [10].
The total cost was 20, and this is the minimum possible.
Example 2:
Input: stones = [3,2,4,1], K = 3
Output: -1
Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
Example 3:
Input: stones = [3,5,1,2,6], K = 3
Output: 25
Explanation:
We start with [3, 5, 1, 2, 6].
We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].
We merge [3, 8, 6] for a cost of 17, and we are left with [17].
The total cost was 25, and this is the minimum possible.
Note:
1 <= stones.length <= 30
2 <= K <= 30
1 <= stones[i] <= 100
|
class Solution:
def mergeStones(self, stones: List[int], K: int) -> int:
if (len(stones) - 1) % (K - 1) != 0:
return -1
prefix = [0]
for stone in stones:
prefix.append(prefix[-1] + stone)
memo = {}
def recur(i: int, j: int, m: int):
key = str(i) + ',' + str(j) + ',' + str(m)
if key in memo:
return memo[key]
if (j - i + 1 - m) % (K - 1):
return 91111111
if (j - i + 1) < K:
memo[key] = 0
return 0
if m == 1:
if j - i + 1 == K:
memo[key] = prefix[j + 1] - prefix[i]
return memo[key]
else:
return recur(i, j, K) + prefix[j + 1] - prefix[i]
min_sum = 91111111
for mid in range(i, j, K - 1):
cur_sum = recur(i, mid, 1) + recur(mid + 1, j, m - 1)
min_sum = min(min_sum, cur_sum)
memo[key] = min_sum
return min_sum
return recur(0, len(stones) - 1, 1)
|
There are N piles of stones arranged in a row. The i-th pile has stones[i] stones.
A move consists of merging exactly K consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these K piles.
Find the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1.
Example 1:
Input: stones = [3,2,4,1], K = 2
Output: 20
Explanation:
We start with [3, 2, 4, 1].
We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].
We merge [4, 1] for a cost of 5, and we are left with [5, 5].
We merge [5, 5] for a cost of 10, and we are left with [10].
The total cost was 20, and this is the minimum possible.
Example 2:
Input: stones = [3,2,4,1], K = 3
Output: -1
Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
Example 3:
Input: stones = [3,5,1,2,6], K = 3
Output: 25
Explanation:
We start with [3, 5, 1, 2, 6].
We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].
We merge [3, 8, 6] for a cost of 17, and we are left with [17].
The total cost was 25, and this is the minimum possible.
Note:
1 <= stones.length <= 30
2 <= K <= 30
1 <= stones[i] <= 100
|
from typing import List
import numpy
import sys
import bisect
class Solution:
def mergeStones(self, stones: List[int], K: int) -> int:
tmp = 0
n = len(stones)
dims = (n, n)
dp = numpy.zeros(dims)
presum = numpy.zeros(n+1)
if (n - 1) % (K - 1) != 0:
return -1
for index, stone in enumerate(stones):
tmp += stone
presum[index+1] = tmp
for rlen in range(K, n + 1):
for i in range(0, n - rlen + 1):
end = i + rlen - 1
dp[i][end] = sys.maxsize
for j in range(i, end, K - 1):
dp[i][end] = min(dp[i][end], dp[i][j] + dp[j + 1][end])
if (rlen - 1) % (K - 1) == 0:
dp[i][end] += presum[end+1] - presum[i]
return int(dp[0][n - 1])
|
There are N piles of stones arranged in a row. The i-th pile has stones[i] stones.
A move consists of merging exactly K consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these K piles.
Find the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1.
Example 1:
Input: stones = [3,2,4,1], K = 2
Output: 20
Explanation:
We start with [3, 2, 4, 1].
We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].
We merge [4, 1] for a cost of 5, and we are left with [5, 5].
We merge [5, 5] for a cost of 10, and we are left with [10].
The total cost was 20, and this is the minimum possible.
Example 2:
Input: stones = [3,2,4,1], K = 3
Output: -1
Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
Example 3:
Input: stones = [3,5,1,2,6], K = 3
Output: 25
Explanation:
We start with [3, 5, 1, 2, 6].
We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].
We merge [3, 8, 6] for a cost of 17, and we are left with [17].
The total cost was 25, and this is the minimum possible.
Note:
1 <= stones.length <= 30
2 <= K <= 30
1 <= stones[i] <= 100
|
class Solution:
def mergeStones(self, stones: List[int], K: int) -> int:
n = len(stones)
dp = [[[math.inf for k in range(K + 1)] for j in range(n)] for i in range(n)]
# dp[i][j][k]: min cost of merging from i to j (inclusive) and finally having k piles
for i in range(n):
dp[i][i][1] = 0
pre_sum = [0] * n
pre_sum[0] = stones[0]
for i in range(1, n):
pre_sum[i] = pre_sum[i - 1] + stones[i]
def range_sum(i, j):
if i == 0:
return pre_sum[j]
else:
return pre_sum[j] - pre_sum[i - 1]
for merge_len in range(2, n + 1): # 枚举区间长度
for start in range(n - merge_len + 1): # 枚举区间左端点
end = start + merge_len - 1 # 区间右端点
for k in range(2, K + 1):
for middle in range(start, end, K - 1): # 枚举分割点,左区间start~middle,右区间middle+1~end
dp[start][end][k] = min(dp[start][end][k], dp[start][middle][1] + dp[middle + 1][end][k - 1])
if dp[start][end][K] < math.inf: # 可以make a move,merge start ~ end 成 1 个pile
dp[start][end][1] = dp[start][end][K] + range_sum(start, end)
return dp[0][n-1][1] if dp[0][n-1][1] < math.inf else -1
|
There are N piles of stones arranged in a row. The i-th pile has stones[i] stones.
A move consists of merging exactly K consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these K piles.
Find the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1.
Example 1:
Input: stones = [3,2,4,1], K = 2
Output: 20
Explanation:
We start with [3, 2, 4, 1].
We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].
We merge [4, 1] for a cost of 5, and we are left with [5, 5].
We merge [5, 5] for a cost of 10, and we are left with [10].
The total cost was 20, and this is the minimum possible.
Example 2:
Input: stones = [3,2,4,1], K = 3
Output: -1
Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
Example 3:
Input: stones = [3,5,1,2,6], K = 3
Output: 25
Explanation:
We start with [3, 5, 1, 2, 6].
We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].
We merge [3, 8, 6] for a cost of 17, and we are left with [17].
The total cost was 25, and this is the minimum possible.
Note:
1 <= stones.length <= 30
2 <= K <= 30
1 <= stones[i] <= 100
|
class Solution:
def mergeStones(self, stones: List[int], K: int) -> int:
# dp[i][j][k]: min cost of merging from i to j and finally having k piles
n = len(stones)
dp = [[[math.inf for k in range(K + 1)] for _ in range(n)] for _ in range(n)]
for i in range(n):
dp[i][i][1] = 0
pre_sum = [0] * n
pre_sum[0] = stones[0]
for i in range(1, n):
pre_sum[i] = pre_sum[i - 1] + stones[i]
def range_sum(i, j):
if i == 0:
return pre_sum[j]
else:
return pre_sum[j] - pre_sum[i - 1]
for length in range(2, n+1):
for i in range(n - length + 1):
j = i + length - 1
# 最少两个,最多K个pile
for k in range(2, K + 1):
for middle in range(i, j, K-1):
# 分成 1 和 k-1堆,合并起来是 k
dp[i][j][k] = min(dp[i][j][k], dp[i][middle][1] + dp[middle + 1][j][k - 1])
if dp[i][j][K] < math.inf:
# 合并成 1个pile
dp[i][j][1] = dp[i][j][K] + range_sum(i, j)
return dp[0][n-1][1] if dp[0][n - 1][1] < math.inf else -1
|
There are N piles of stones arranged in a row. The i-th pile has stones[i] stones.
A move consists of merging exactly K consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these K piles.
Find the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1.
Example 1:
Input: stones = [3,2,4,1], K = 2
Output: 20
Explanation:
We start with [3, 2, 4, 1].
We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].
We merge [4, 1] for a cost of 5, and we are left with [5, 5].
We merge [5, 5] for a cost of 10, and we are left with [10].
The total cost was 20, and this is the minimum possible.
Example 2:
Input: stones = [3,2,4,1], K = 3
Output: -1
Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
Example 3:
Input: stones = [3,5,1,2,6], K = 3
Output: 25
Explanation:
We start with [3, 5, 1, 2, 6].
We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].
We merge [3, 8, 6] for a cost of 17, and we are left with [17].
The total cost was 25, and this is the minimum possible.
Note:
1 <= stones.length <= 30
2 <= K <= 30
1 <= stones[i] <= 100
|
class Solution:
def mergeStones(self, stones: List[int], K: int) -> int:
n = len(stones)
dp = [[[math.inf for k in range(K + 1)] for j in range(n)] for i in range(n)]
# dp[i][j][k]: min cost of merging from i to j and finally having k piles
for i in range(n):
dp[i][i][1] = 0
pre_sum = [0] * (n + 1)
for i in range(1, n + 1):
pre_sum[i] = pre_sum[i - 1] + stones[i - 1]
for merge_len in range(2, n + 1):
for start in range(n - merge_len + 1):
end = start + merge_len - 1
for k in range(2, K + 1):
for middle in range(start, end, K-1):
dp[start][end][k] = min(dp[start][end][k], dp[start][middle][1] + dp[middle + 1][end][k - 1])
if dp[start][end][K] < math.inf:
dp[start][end][1] = dp[start][end][K] + pre_sum[end + 1] - pre_sum[start]
return dp[0][n-1][1] if dp[0][n-1][1] < math.inf else -1
|
There are N piles of stones arranged in a row. The i-th pile has stones[i] stones.
A move consists of merging exactly K consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these K piles.
Find the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1.
Example 1:
Input: stones = [3,2,4,1], K = 2
Output: 20
Explanation:
We start with [3, 2, 4, 1].
We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].
We merge [4, 1] for a cost of 5, and we are left with [5, 5].
We merge [5, 5] for a cost of 10, and we are left with [10].
The total cost was 20, and this is the minimum possible.
Example 2:
Input: stones = [3,2,4,1], K = 3
Output: -1
Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
Example 3:
Input: stones = [3,5,1,2,6], K = 3
Output: 25
Explanation:
We start with [3, 5, 1, 2, 6].
We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].
We merge [3, 8, 6] for a cost of 17, and we are left with [17].
The total cost was 25, and this is the minimum possible.
Note:
1 <= stones.length <= 30
2 <= K <= 30
1 <= stones[i] <= 100
|
class Solution:
def mergeStones(self, stones: List[int], K: int) -> int:
n = len(stones)
inf = float('inf')
if (n - 1) % (K - 1) is not 0:
return -1
prefix = [0] * (n + 1)
for i in range(1, n + 1):
prefix[i] = prefix[i - 1] + stones[i - 1]
@lru_cache(None)
def dp(i, j, k):
if i == j:
# cost to make one pile from one pile is 0, otherwise impossible
return 0 if k == 1 else inf
if k == 1:
return dp(i, j, K) + prefix[j + 1] - prefix[i]
return min(dp(i, m, 1) + dp(m + 1, j, k - 1) for m in range(i, j))
return dp(0, n - 1, 1)
|
There are N piles of stones arranged in a row. The i-th pile has stones[i] stones.
A move consists of merging exactly K consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these K piles.
Find the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1.
Example 1:
Input: stones = [3,2,4,1], K = 2
Output: 20
Explanation:
We start with [3, 2, 4, 1].
We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].
We merge [4, 1] for a cost of 5, and we are left with [5, 5].
We merge [5, 5] for a cost of 10, and we are left with [10].
The total cost was 20, and this is the minimum possible.
Example 2:
Input: stones = [3,2,4,1], K = 3
Output: -1
Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
Example 3:
Input: stones = [3,5,1,2,6], K = 3
Output: 25
Explanation:
We start with [3, 5, 1, 2, 6].
We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].
We merge [3, 8, 6] for a cost of 17, and we are left with [17].
The total cost was 25, and this is the minimum possible.
Note:
1 <= stones.length <= 30
2 <= K <= 30
1 <= stones[i] <= 100
|
class Solution:
def mergeStones(self, stones: List[int], K: int) -> int:
N = len(stones)
presum = [0 for _ in range(N + 1)]
dp = [[[math.inf for _ in range(K + 1)] for _ in range(N)] for _ in range(N)]
if (N - 1) % (K - 1) != 0:
return -1
for i in range(N):
presum[i + 1] = presum[i] + stones[i]
for i in range(N):
dp[i][i][1] = 0
for length in range(2, N + 1):
for start in range(N - length + 1):
end = start + length - 1
for mid in range(start, end):
for k in range(2, K + 1):
if k > length:
continue
if dp[start][mid][1] == math.inf or dp[mid + 1][end][k - 1] == math.inf:
continue
dp[start][end][k] = min(dp[start][end][k], dp[start][mid][1] + dp[mid + 1][end][k - 1])
if dp[start][end][K] != math.inf:
dp[start][end][1] = dp[start][end][K] + presum[end + 1] - presum[start]
if dp[0][N - 1][1] == math.inf:
return -1
return dp[0][N - 1][1]
|
There are N piles of stones arranged in a row. The i-th pile has stones[i] stones.
A move consists of merging exactly K consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these K piles.
Find the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1.
Example 1:
Input: stones = [3,2,4,1], K = 2
Output: 20
Explanation:
We start with [3, 2, 4, 1].
We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].
We merge [4, 1] for a cost of 5, and we are left with [5, 5].
We merge [5, 5] for a cost of 10, and we are left with [10].
The total cost was 20, and this is the minimum possible.
Example 2:
Input: stones = [3,2,4,1], K = 3
Output: -1
Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
Example 3:
Input: stones = [3,5,1,2,6], K = 3
Output: 25
Explanation:
We start with [3, 5, 1, 2, 6].
We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].
We merge [3, 8, 6] for a cost of 17, and we are left with [17].
The total cost was 25, and this is the minimum possible.
Note:
1 <= stones.length <= 30
2 <= K <= 30
1 <= stones[i] <= 100
|
class Solution:
def mergeStones(self, stones: List[int], K: int) -> int:
if (len(stones) - 1) % (K - 1) != 0:
return -1
presum = 0
presum_list = [presum]
for cost in stones:
presum += cost
presum_list.append(presum)
# dp[i][j][k]: cost that merges into k piles: from ith pile to jth pile
n = len(stones)
dp = [[[math.inf] * (K + 1) for _ in range(n)] for _ in range(n)]
for i in range(n):
dp[i][i][1] = 0
for pile_length in range(1, n + 1):
# pile_length = j - i + 1
for i in range(n - pile_length + 1):
j = pile_length + i - 1
for possible_k in range(2, min(pile_length, K) + 1):
for t in range(i, j):
dp[i][j][possible_k] = min(dp[i][j][possible_k], dp[i][t][possible_k - 1] + dp[t + 1][j][1])
dp[i][j][1] = min(dp[i][j][1], dp[i][j][K] + presum_list[j + 1] - presum_list[i])
return dp[0][n - 1][1]
|
There are N piles of stones arranged in a row. The i-th pile has stones[i] stones.
A move consists of merging exactly K consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these K piles.
Find the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1.
Example 1:
Input: stones = [3,2,4,1], K = 2
Output: 20
Explanation:
We start with [3, 2, 4, 1].
We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].
We merge [4, 1] for a cost of 5, and we are left with [5, 5].
We merge [5, 5] for a cost of 10, and we are left with [10].
The total cost was 20, and this is the minimum possible.
Example 2:
Input: stones = [3,2,4,1], K = 3
Output: -1
Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
Example 3:
Input: stones = [3,5,1,2,6], K = 3
Output: 25
Explanation:
We start with [3, 5, 1, 2, 6].
We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].
We merge [3, 8, 6] for a cost of 17, and we are left with [17].
The total cost was 25, and this is the minimum possible.
Note:
1 <= stones.length <= 30
2 <= K <= 30
1 <= stones[i] <= 100
|
class Solution:
def mergeStones(self, stones: List[int], K: int) -> int:
# Time Complexity: O(N^3 K)
self.dp = {}
self.prefix = [0] + list(itertools.accumulate(stones))
ret = self.merge(stones, 0, len(stones) - 1, 1, K)
return ret
def merge(self, stones, start: int, end: int, num_parts: int, K: int):
if (start, end, num_parts) in self.dp:
return self.dp[(start, end, num_parts)]
if end - start + 1 < num_parts:
return -1
if end - start + 1 == num_parts:
return 0
window_sum = self.prefix[end + 1] - self.prefix[start]
if num_parts == 1:
split = self.merge(stones, start, end, K, K)
if split == -1:
ret = -1
else:
ret = window_sum + split
else:
candidates = []
for i in range(start, end):
left = self.merge(stones, start, i, 1, K)
right = self.merge(stones, i + 1, end, num_parts - 1, K)
if left >= 0 and right >= 0:
candidates.append(left + right)
if candidates:
ret = min(candidates)
else:
ret = -1
self.dp[(start, end, num_parts)] = ret
return ret
|
There are N piles of stones arranged in a row. The i-th pile has stones[i] stones.
A move consists of merging exactly K consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these K piles.
Find the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1.
Example 1:
Input: stones = [3,2,4,1], K = 2
Output: 20
Explanation:
We start with [3, 2, 4, 1].
We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].
We merge [4, 1] for a cost of 5, and we are left with [5, 5].
We merge [5, 5] for a cost of 10, and we are left with [10].
The total cost was 20, and this is the minimum possible.
Example 2:
Input: stones = [3,2,4,1], K = 3
Output: -1
Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
Example 3:
Input: stones = [3,5,1,2,6], K = 3
Output: 25
Explanation:
We start with [3, 5, 1, 2, 6].
We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].
We merge [3, 8, 6] for a cost of 17, and we are left with [17].
The total cost was 25, and this is the minimum possible.
Note:
1 <= stones.length <= 30
2 <= K <= 30
1 <= stones[i] <= 100
|
# 1000. Minimum Cost to Merge Stones
class Solution:
def mergeStones(self, stones: List[int], K: int) -> int:
N = len(stones)
if (N - 1) % (K - 1):
return -1
dp = [[0] * N for _ in range(N)]
for l in range(K, N+1):
for i in range(N-l+1):
dp[i][i+l-1] = float('inf')
for x in range(i, i+l-1, K-1):
dp[i][i+l-1] = min(dp[i][i+l-1], dp[i][x] + dp[x+1][i+l-1])
dp[i][i+l-1] += (sum(stones[i:i+l]) if (l-1)%(K-1) == 0 else 0)
return dp[0][N-1]
|
There are N piles of stones arranged in a row. The i-th pile has stones[i] stones.
A move consists of merging exactly K consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these K piles.
Find the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1.
Example 1:
Input: stones = [3,2,4,1], K = 2
Output: 20
Explanation:
We start with [3, 2, 4, 1].
We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].
We merge [4, 1] for a cost of 5, and we are left with [5, 5].
We merge [5, 5] for a cost of 10, and we are left with [10].
The total cost was 20, and this is the minimum possible.
Example 2:
Input: stones = [3,2,4,1], K = 3
Output: -1
Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
Example 3:
Input: stones = [3,5,1,2,6], K = 3
Output: 25
Explanation:
We start with [3, 5, 1, 2, 6].
We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].
We merge [3, 8, 6] for a cost of 17, and we are left with [17].
The total cost was 25, and this is the minimum possible.
Note:
1 <= stones.length <= 30
2 <= K <= 30
1 <= stones[i] <= 100
|
class Solution:
def mergeStones(self, stones, k):
# quick check to see if this number of piles can be merged.
if (len(stones)-1)%(k-1):
return -1
cost = [[None]*len(stones) for _ in stones]
def subCost(left, right):
# Base case: there is no cost to \"merging\" one pile
if left == right:
return 0
if cost[left][right] != None:
return cost[left][right]
# Base case: a single merge is just the sum of the elements.
if (right - left + 1) == k:
cost[left][right] = sum(stones[left:right+1])
return cost[left][right]
# find k-1 division points. Each division except the last is the start index of a sub-array
# ie. if stones = [ 0, 1, 2, 3, 4, 5, 6, 7, 8 ], left = 0 right = 8 divs = [0, 3, 8, 9]
# then sub-arrays are as follows: [0, 1, 2] [3, 4, 5, 6, 7] [8]
# the above divs would incidentally be valid for k = 3.
divs = [ left + i for i in range(k+1)]
divs[-1] = right + 1 # set the last divider to one past the subarray.
# for example above, divs is initialized to -> [0, 1, 2, 9]. The first and last divider never change
def moveDividers():
# loop through dividers to move, starting at last one.
# if the last one is at the end, move the next one up.
def moveDivider(i):
if i == 0:
return False
# if the div we're looking at is smashing all dividers to its right against the right end of the array.
# If k = 3, i = 1, we have 1 divider to our right. Leave 1 space for each divider to our right.
# division 0 stays at 0
# div 1 can go to 2. = right - (k - 1 - i)
if divs[i] == ( right - (k - 1 - i)):
# switch to the next divider to the left
return moveDivider(i-1)
# move this divider to the next usable spot given where the left neighbor div is.
divs[i] += 1
while (divs[i] - divs[i-1] - 1)%(k-1):
divs[i] += 1
# stack all following divs next to each other and this one. []
for j in range(i+1, len(divs)-1):
divs[j] = divs[j-1] + 1
return True
# start by moving the rightmost divider
return moveDivider(len(divs) - 2)
best = float('inf')
while 1:
subSum = 0
for div_i in range(len(divs)-1):
subSum += subCost(divs[div_i], divs[div_i+1] - 1)
best = min(best, subSum)
if not moveDividers():
break
result = best + sum(stones[left:right+1])
cost[left][right] = result
return result
result = subCost(0, len(stones)-1)
#print(cost)
return result
|
There are N piles of stones arranged in a row. The i-th pile has stones[i] stones.
A move consists of merging exactly K consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these K piles.
Find the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1.
Example 1:
Input: stones = [3,2,4,1], K = 2
Output: 20
Explanation:
We start with [3, 2, 4, 1].
We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].
We merge [4, 1] for a cost of 5, and we are left with [5, 5].
We merge [5, 5] for a cost of 10, and we are left with [10].
The total cost was 20, and this is the minimum possible.
Example 2:
Input: stones = [3,2,4,1], K = 3
Output: -1
Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
Example 3:
Input: stones = [3,5,1,2,6], K = 3
Output: 25
Explanation:
We start with [3, 5, 1, 2, 6].
We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].
We merge [3, 8, 6] for a cost of 17, and we are left with [17].
The total cost was 25, and this is the minimum possible.
Note:
1 <= stones.length <= 30
2 <= K <= 30
1 <= stones[i] <= 100
|
class Solution:
def mergeStones(self, stones: List[int], K: int) -> int:
# Time Complexity: O(N^3 K)
# Space Complexity: O(N^2 K)
self.dp = {}
self.prefix = [0] + list(itertools.accumulate(stones))
ret = self.merge(stones, 0, len(stones) - 1, 1, K)
return ret
def merge(self, stones, start: int, end: int, num_parts: int, K: int):
if (start, end, num_parts) in self.dp:
return self.dp[(start, end, num_parts)]
if end - start + 1 < num_parts:
return -1
if end - start + 1 == num_parts:
return 0
window_sum = self.prefix[end + 1] - self.prefix[start]
if num_parts == 1:
split = self.merge(stones, start, end, K, K)
if split == -1:
ret = -1
else:
ret = window_sum + split
else:
candidates = []
for i in range(start, end):
left = self.merge(stones, start, i, 1, K)
right = self.merge(stones, i + 1, end, num_parts - 1, K)
if left >= 0 and right >= 0:
candidates.append(left + right)
if candidates:
ret = min(candidates)
else:
ret = -1
self.dp[(start, end, num_parts)] = ret
return ret
|
There are N piles of stones arranged in a row. The i-th pile has stones[i] stones.
A move consists of merging exactly K consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these K piles.
Find the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1.
Example 1:
Input: stones = [3,2,4,1], K = 2
Output: 20
Explanation:
We start with [3, 2, 4, 1].
We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].
We merge [4, 1] for a cost of 5, and we are left with [5, 5].
We merge [5, 5] for a cost of 10, and we are left with [10].
The total cost was 20, and this is the minimum possible.
Example 2:
Input: stones = [3,2,4,1], K = 3
Output: -1
Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
Example 3:
Input: stones = [3,5,1,2,6], K = 3
Output: 25
Explanation:
We start with [3, 5, 1, 2, 6].
We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].
We merge [3, 8, 6] for a cost of 17, and we are left with [17].
The total cost was 25, and this is the minimum possible.
Note:
1 <= stones.length <= 30
2 <= K <= 30
1 <= stones[i] <= 100
|
class Solution:
def mergeStones(self, stones: List[int], K: int) -> int:
self.dp = {}
ret = self.merge(stones, 0, len(stones) - 1, 1, K)
return ret
def merge(self, stones, start: int, end: int, num_parts: int, K: int):
if (start, end, num_parts) in self.dp:
return self.dp[(start, end, num_parts)]
if end - start + 1 < num_parts:
return -1
if end - start + 1 == num_parts:
return 0
window_sum = sum(stones[start:end + 1])
if num_parts == 1:
split = self.merge(stones, start, end, K, K)
if split == -1:
ret = -1
else:
ret = window_sum + split
else:
candidates = []
for i in range(start, end):
left = self.merge(stones, start, i, 1, K)
right = self.merge(stones, i + 1, end, num_parts - 1, K)
if left >= 0 and right >= 0:
candidates.append(left + right)
if candidates:
ret = min(candidates)
else:
ret = -1
self.dp[(start, end, num_parts)] = ret
return ret
|
There are N piles of stones arranged in a row. The i-th pile has stones[i] stones.
A move consists of merging exactly K consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these K piles.
Find the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1.
Example 1:
Input: stones = [3,2,4,1], K = 2
Output: 20
Explanation:
We start with [3, 2, 4, 1].
We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].
We merge [4, 1] for a cost of 5, and we are left with [5, 5].
We merge [5, 5] for a cost of 10, and we are left with [10].
The total cost was 20, and this is the minimum possible.
Example 2:
Input: stones = [3,2,4,1], K = 3
Output: -1
Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
Example 3:
Input: stones = [3,5,1,2,6], K = 3
Output: 25
Explanation:
We start with [3, 5, 1, 2, 6].
We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].
We merge [3, 8, 6] for a cost of 17, and we are left with [17].
The total cost was 25, and this is the minimum possible.
Note:
1 <= stones.length <= 30
2 <= K <= 30
1 <= stones[i] <= 100
|
class Solution:
def mergeStones(self, stones: List[int], K: int) -> int:
n = len(stones)
inf = float('inf')
prefix = [0] * (n + 1)
for i in range(n):
prefix[i + 1] = prefix[i] + stones[i]
import functools
@functools.lru_cache(None)
def dp(i, j, m):
if i == j:
return 0 if m == 1 else inf
if m == 1:
return dp(i, j, K) + prefix[j + 1] - prefix[i]
return min(dp(i, mid, 1) + dp(mid + 1, j, m - 1) for mid in range(i, j))
res = dp(0, n - 1, 1)
return res if res < inf else -1
|
There are N piles of stones arranged in a row. The i-th pile has stones[i] stones.
A move consists of merging exactly K consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these K piles.
Find the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1.
Example 1:
Input: stones = [3,2,4,1], K = 2
Output: 20
Explanation:
We start with [3, 2, 4, 1].
We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].
We merge [4, 1] for a cost of 5, and we are left with [5, 5].
We merge [5, 5] for a cost of 10, and we are left with [10].
The total cost was 20, and this is the minimum possible.
Example 2:
Input: stones = [3,2,4,1], K = 3
Output: -1
Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
Example 3:
Input: stones = [3,5,1,2,6], K = 3
Output: 25
Explanation:
We start with [3, 5, 1, 2, 6].
We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].
We merge [3, 8, 6] for a cost of 17, and we are left with [17].
The total cost was 25, and this is the minimum possible.
Note:
1 <= stones.length <= 30
2 <= K <= 30
1 <= stones[i] <= 100
|
class Solution:
def mergeStones(self, stones: List[int], K: int) -> int:
n = len(stones)
if K > 2 and n % (K - 1) != 1:
return -1
dp = [[[math.inf] * (K + 1) for i in range(n)] for j in range(n)]
for i in range(n):
dp[i][i][1] = 0
presum = [stones[0]]
for i in range(1, n):
presum.append(presum[i - 1] + stones[i])
def stones_in_range(i, j):
return presum[j] - presum[i - 1] if i > 0 else presum[j]
for rangelen in range(2, n + 1):
for start in range(n + 1 - rangelen):
end = start + rangelen - 1
for k in range(2, K + 1):
for divide in range(start, end, K - 1):
dp[start][end][k] = min(dp[start][end][k], dp[start][divide][1] + dp[divide + 1][end][k - 1])
print(start, end, k, divide, dp[start][end][k])
if dp[start][end][K] < math.inf:
dp[start][end][1] = dp[start][end][K] + stones_in_range(start, end)
return dp[0][n - 1][1]
|
There are N piles of stones arranged in a row. The i-th pile has stones[i] stones.
A move consists of merging exactly K consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these K piles.
Find the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1.
Example 1:
Input: stones = [3,2,4,1], K = 2
Output: 20
Explanation:
We start with [3, 2, 4, 1].
We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].
We merge [4, 1] for a cost of 5, and we are left with [5, 5].
We merge [5, 5] for a cost of 10, and we are left with [10].
The total cost was 20, and this is the minimum possible.
Example 2:
Input: stones = [3,2,4,1], K = 3
Output: -1
Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
Example 3:
Input: stones = [3,5,1,2,6], K = 3
Output: 25
Explanation:
We start with [3, 5, 1, 2, 6].
We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].
We merge [3, 8, 6] for a cost of 17, and we are left with [17].
The total cost was 25, and this is the minimum possible.
Note:
1 <= stones.length <= 30
2 <= K <= 30
1 <= stones[i] <= 100
|
class Solution:
def mergeStones(self, stones: List[int], K: int) -> int:
n = len(stones)
if (n - 1) % (K - 1):
return -1
s = [0]
for num in stones:
s.append(s[-1] + num)
dp = [[0] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(i + 1, n):
dp[i][j] = float('inf')
for m in range(i, j, K - 1):
dp[i][j] = min(dp[i][j], dp[i][m] + dp[m + 1][j] + (0 if (j - i) % (K - 1) else s[j + 1] - s[i]))
return -1 if dp[0][-1] == float('inf') else dp[0][-1]
@functools.lru_cache(None)
def f(i, j):
if i == j:
return 0
ans = float('inf')
m = i
while m < j:
ans = min(ans, f(i, m) + f(m + 1, j) + (0 if (j - i) % (K - 1) else s[j + 1] - s[i]))
m += K - 1
return ans
ans = f(0, n - 1)
return -1 if ans == float('inf') else ans
|
There are N piles of stones arranged in a row. The i-th pile has stones[i] stones.
A move consists of merging exactly K consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these K piles.
Find the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1.
Example 1:
Input: stones = [3,2,4,1], K = 2
Output: 20
Explanation:
We start with [3, 2, 4, 1].
We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].
We merge [4, 1] for a cost of 5, and we are left with [5, 5].
We merge [5, 5] for a cost of 10, and we are left with [10].
The total cost was 20, and this is the minimum possible.
Example 2:
Input: stones = [3,2,4,1], K = 3
Output: -1
Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
Example 3:
Input: stones = [3,5,1,2,6], K = 3
Output: 25
Explanation:
We start with [3, 5, 1, 2, 6].
We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].
We merge [3, 8, 6] for a cost of 17, and we are left with [17].
The total cost was 25, and this is the minimum possible.
Note:
1 <= stones.length <= 30
2 <= K <= 30
1 <= stones[i] <= 100
|
class Solution:
def mergeStones(self, stones: List[int], K: int) -> int:
n = len(stones)
if (n-1)%(K-1) != 0:
return -1
dp = [[0]*n for i in range(n)]
sums = [0]*(n+1)
for i in range(1, n+1):
sums[i] = sums[i-1] + stones[i-1]
for l in range(K, n+1):
for i in range(n-l+1):
j = i+l-1
dp[i][j] = float('inf')
for t in range(i, j, K-1):
dp[i][j] = min(dp[i][j], dp[i][t]+dp[t+1][j])
if (j-i)%(K-1) == 0:
dp[i][j] += sums[j+1] - sums[i]
return dp[0][n-1]
|
There are N piles of stones arranged in a row. The i-th pile has stones[i] stones.
A move consists of merging exactly K consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these K piles.
Find the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1.
Example 1:
Input: stones = [3,2,4,1], K = 2
Output: 20
Explanation:
We start with [3, 2, 4, 1].
We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].
We merge [4, 1] for a cost of 5, and we are left with [5, 5].
We merge [5, 5] for a cost of 10, and we are left with [10].
The total cost was 20, and this is the minimum possible.
Example 2:
Input: stones = [3,2,4,1], K = 3
Output: -1
Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
Example 3:
Input: stones = [3,5,1,2,6], K = 3
Output: 25
Explanation:
We start with [3, 5, 1, 2, 6].
We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].
We merge [3, 8, 6] for a cost of 17, and we are left with [17].
The total cost was 25, and this is the minimum possible.
Note:
1 <= stones.length <= 30
2 <= K <= 30
1 <= stones[i] <= 100
|
class Solution:
def mergeStones(self, stones: List[int], K: int) -> int:
n = len(stones)
if (n - 1) % (K - 1):
return -1
prefix = [0]*(n+1)
for i in range(1, n+1):
prefix[i] = prefix[i-1] + stones[i-1]
import functools
@functools.lru_cache(None)
def dp(i, j):
if j - i + 1 < K:
return 0
res = min(dp(i, mid) + dp(mid+1, j) for mid in range(i, j, K-1))
if (j - i) % (K - 1) == 0:
res += prefix[j + 1] - prefix[i]
return res
return dp(0, n-1)
# n = len(stones)
# if (n - 1) % (K - 1): return -1
# prefix = [0] * (n + 1)
# for i in range(n):
# prefix[i + 1] = prefix[i] + stones[i]
# import functools
# @functools.lru_cache(None)
# def dp(i, j):
# if j - i + 1 < K: return 0
# res = min(dp(i, mid) + dp(mid + 1, j) for mid in range(i, j, K - 1))
# if (j - i) % (K - 1) == 0:
# res += prefix[j + 1] - prefix[i]
# return res
# return dp(0, n - 1)
|
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3, t = 0
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1, t = 2
Output: true
Example 3:
Input: nums = [1,5,9,1,5,9], k = 2, t = 3
Output: false
|
class Solution:
def containsNearbyAlmostDuplicate(self, nums, k, t):
"""
:type nums: List[int]
:type k: int
:type t: int
:rtype: bool
"""
if len(nums) < 2 or k <= 0 or t < 0: return False
if t == 0:
visited = set()
for i, n in enumerate(nums):
if n in visited: return True
visited.add(n)
if i >= k: visited.remove(nums[i-k])
return False
bucket = {}
for i, n in enumerate(nums):
b = n // t
if b in bucket: return True
if b+1 in bucket and abs(bucket[b+1]-n) <= t: return True
if b-1 in bucket and abs(bucket[b-1]-n) <= t: return True
bucket[b] = n
if i >= k: del bucket[nums[i-k]//t]
return False
|
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3, t = 0
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1, t = 2
Output: true
Example 3:
Input: nums = [1,5,9,1,5,9], k = 2, t = 3
Output: false
|
class Solution:
def containsNearbyAlmostDuplicate(self, nums, k, t):
"""
:type nums: List[int]
:type k: int
:type t: int
:rtype: bool
"""
nums2 = [(n, i) for i, n in enumerate(nums)]
nums2 = sorted(nums2)
print(nums2)
for i in range(1, len(nums2)):
j = i-1
a, n = nums2[j]
b, m = nums2[i]
while abs(a-b) <= t:
if abs(n-m) <= k:
return True
j -= 1
if j < 0:
break
a, n = nums2[j]
return False
|
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3, t = 0
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1, t = 2
Output: true
Example 3:
Input: nums = [1,5,9,1,5,9], k = 2, t = 3
Output: false
|
class Solution(object):
def containsNearbyAlmostDuplicate(self, nums, k, t):
"""
:type nums: List[int]
:type k: int
:type t: int
:rtype: bool
"""
if k < 1 or t < 0:
return False
import sys
bh = {}
# To prevent 0 as a divisor
w = t+1
for i in range(len(nums)):
n_i = nums[i]
n_i_w = n_i // w
if n_i_w in bh:
return True
if n_i_w-1 in bh and abs(n_i - bh[n_i_w-1]) < w:
return True
if n_i_w+1 in bh and abs(n_i - bh[n_i_w+1]) < w:
return True
bh[n_i_w] = nums[i]
if len(bh) > k:
del bh[(nums[i - k]) // w]
return False
|
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3, t = 0
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1, t = 2
Output: true
Example 3:
Input: nums = [1,5,9,1,5,9], k = 2, t = 3
Output: false
|
class Solution:
def containsNearbyAlmostDuplicate(self, nums, k, t):
"""
:type nums: List[int]
:type k: int
:type t: int
:rtype: bool
"""
if t<0:
return False
w = t+1
d = {}
for i in range(0, len(nums)):
m = nums[i]//w
#print(m,d)
if m in d:
return True
if m-1 in d and abs(nums[i]-d[m-1])<=t:
return True
if m+1 in d and abs(nums[i]-d[m+1])<=t:
return True
d[m] = nums[i]
if i>=k:
del d[nums[i-k]//w]
return False
|
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3, t = 0
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1, t = 2
Output: true
Example 3:
Input: nums = [1,5,9,1,5,9], k = 2, t = 3
Output: false
|
class Solution:
def containsNearbyAlmostDuplicate(self, nums, k, t):
"""
:type nums: List[int]
:type k: int
:type t: int
:rtype: bool
"""
if t < 0: return False
n = len(nums)
buckets = {}
w = t + 1
for i in range(n):
bucket_num = nums[i] // w
if bucket_num in buckets:
return True
if bucket_num - 1 in buckets and abs(nums[i] - buckets[bucket_num - 1]) < w:
return True
if bucket_num + 1 in buckets and abs(nums[i] - buckets[bucket_num + 1]) < w:
return True
buckets[bucket_num] = nums[i]
if i >= k: del buckets[nums[i-k]//w]
return False
|
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3, t = 0
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1, t = 2
Output: true
Example 3:
Input: nums = [1,5,9,1,5,9], k = 2, t = 3
Output: false
|
class Solution:
def equalSol(self, nums, k):
if k == 0:
return False
d = {}
for i in range(len(nums)):
if nums[i] in d.keys() and abs(i - d[nums[i]]) <= k:
return True
else:
d[nums[i]] = i
return False
def containsNearbyAlmostDuplicate(self, nums, k, t):
"""
:type nums: List[int]
:type k: int
:type t: int
:rtype: bool
"""
if k == 0:
return False
if t == 0:
return self.equalSol(nums, k)
for i in range(len(nums)):
for j in range(1,(k+1)):
if (i + j) < len(nums) and abs(nums[i] - nums[i+j]) <= t:
return True
if (i - j) >= 0 and abs(nums[i] - nums[i-j]) <=t:
return True
return False
|
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3, t = 0
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1, t = 2
Output: true
Example 3:
Input: nums = [1,5,9,1,5,9], k = 2, t = 3
Output: false
|
class Solution:
def containsNearbyAlmostDuplicate(self, nums, k, t):
"""
:type nums: List[int]
:type k: int
:type t: int
:rtype: bool
"""
buckets = {}
for i, v in enumerate(nums):
bucket_num, offset = (v//t, 1) if t else (v, 0)
for idx in range(bucket_num - offset, bucket_num + offset + 1):
if idx in buckets and abs(buckets[idx] - nums[i]) <= t:
return True
buckets[bucket_num] = nums[i]
if len(buckets) > k:
del buckets[nums[i-k] // t if t else nums[i-k]]
return False
|
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3, t = 0
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1, t = 2
Output: true
Example 3:
Input: nums = [1,5,9,1,5,9], k = 2, t = 3
Output: false
|
class Solution:
def containsNearbyAlmostDuplicate(self, nums, k, t):
"""
:type nums: List[int]
:type k: int
:type t: int
:rtype: bool
"""
if t < 0: return False
n = len(nums)
buckets = {}
w = t + 1
for i in range(n):
bucket_num = nums[i] // w
if bucket_num in buckets:
return True
if bucket_num - 1 in buckets and abs(nums[i] - buckets[bucket_num - 1]) < w:
return True
if bucket_num + 1 in buckets and abs(nums[i] - buckets[bucket_num + 1]) < w:
return True
buckets[bucket_num] = nums[i]
if i >= k: del buckets[nums[i-k]//w]
return False
|
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3, t = 0
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1, t = 2
Output: true
Example 3:
Input: nums = [1,5,9,1,5,9], k = 2, t = 3
Output: false
|
class Solution:
# @param {integer[]} nums
# @param {integer} k
# @param {integer} t
# @return {boolean}
def containsNearbyAlmostDuplicate(self, nums, k, t):
if len(nums) == 0 or len(nums) == 1 or k < 1 or t < 0:
return False
d = collections.OrderedDict()
for i in nums:
key = i if not t else i // t
for j in (d.get(key - 1), d.get(key), d.get(key + 1)):
if j != None and abs(j - i) <= t:
return True
if len(d) == k:
d.popitem(False)
d[key] = i
return False
|
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3, t = 0
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1, t = 2
Output: true
Example 3:
Input: nums = [1,5,9,1,5,9], k = 2, t = 3
Output: false
|
class Solution:
def containsNearbyAlmostDuplicate(self, nums, k, t):
"""
:type nums: List[int]
:type k: int
:type t: int
:rtype: bool
"""
if k < 1 or t < 0:
return False
m = len(nums)
if m == 0:
return False
buckets = {}
_min = 0
for i in range(m):
num = nums[i] - _min
bucket = num // (t + 1)
flag = bucket in buckets \
or (bucket - 1 in buckets and abs(buckets[bucket - 1] - num) <= t) \
or (bucket + 1 in buckets and abs(buckets[bucket + 1] - num) <= t)
if flag:
return True
if len(buckets) >= k:
del buckets[(nums[i - k] - _min) // (t + 1)]
buckets[bucket] = num
return False
|
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3, t = 0
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1, t = 2
Output: true
Example 3:
Input: nums = [1,5,9,1,5,9], k = 2, t = 3
Output: false
|
class Solution:
def containsNearbyAlmostDuplicate(self, nums, k, t):
"""
:type nums: List[int]
:type k: int
:type t: int
:rtype: bool
"""
if t < 0:
return False
d = {}
w = t + 1
for i in range(len(nums)):
b = nums[i] // w
if b in d:
return True
if b - 1 in d and abs(nums[i] - d[b - 1]) < w:
return True
if b + 1 in d and abs(nums[i] - d[b + 1]) < w:
return True
d[b] = nums[i]
if i >= k:
del d[nums[i - k] // w]
return False
|
Given a string s, return the maximum number of unique substrings that the given string can be split into.
You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "ababccc"
Output: 5
Explanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.
Example 2:
Input: s = "aba"
Output: 2
Explanation: One way to split maximally is ['a', 'ba'].
Example 3:
Input: s = "aa"
Output: 1
Explanation: It is impossible to split the string any further.
Constraints:
1 <= s.length <= 16
s contains only lower case English letters.
|
class Solution:
def maxUniqueSplit(self, s: str) -> int:
self.x, n = 0, len(s)
def maxUniqueSplit_(i=0, S=set()):
if s[i:] not in S:
self.x = max(self.x, len(S) + 1)
for j in range(i + 1, n):
if s[i : j] not in S and len(S) + 1 + n - j > self.x:
maxUniqueSplit_(j, S.union({s[i : j]}))
maxUniqueSplit_()
return self.x
|
Given a string s, return the maximum number of unique substrings that the given string can be split into.
You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "ababccc"
Output: 5
Explanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.
Example 2:
Input: s = "aba"
Output: 2
Explanation: One way to split maximally is ['a', 'ba'].
Example 3:
Input: s = "aa"
Output: 1
Explanation: It is impossible to split the string any further.
Constraints:
1 <= s.length <= 16
s contains only lower case English letters.
|
class Solution:
def maxUniqueSplit(self, s: str) -> int:
start = 0
end = 0
se = set()
res = 0
def helper(stn, se, count):
nonlocal res
if not stn:
res = max(res, count)
if len(stn) + count <= res:
return
for i in range(1, len(stn)+1):
if stn[:i] not in se:
helper(stn[i:], se|{stn[:i]}, count + 1)
helper(s, se, 0)
return res
|
Given a string s, return the maximum number of unique substrings that the given string can be split into.
You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "ababccc"
Output: 5
Explanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.
Example 2:
Input: s = "aba"
Output: 2
Explanation: One way to split maximally is ['a', 'ba'].
Example 3:
Input: s = "aa"
Output: 1
Explanation: It is impossible to split the string any further.
Constraints:
1 <= s.length <= 16
s contains only lower case English letters.
|
class Solution:
def maxUniqueSplit(self, s: str, mem=None, seen=None) -> int:
if mem is None:
mem={}
if seen is None:
seen = set()
res = 0
for i in range(0, len(s)):
if s[0:i+1] in seen:
continue
seen.add(s[0:i+1])
res = max(res, 1 + self.maxUniqueSplit(s[i + 1:], mem, seen))
seen.remove(s[0:i+1])
mem[s] = res
return res
|
Given a string s, return the maximum number of unique substrings that the given string can be split into.
You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "ababccc"
Output: 5
Explanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.
Example 2:
Input: s = "aba"
Output: 2
Explanation: One way to split maximally is ['a', 'ba'].
Example 3:
Input: s = "aa"
Output: 1
Explanation: It is impossible to split the string any further.
Constraints:
1 <= s.length <= 16
s contains only lower case English letters.
|
class Solution:
def func(self, s, idx, words):
max_result = 0
for i in range(idx+1, len(s)):
max_result = max(max_result, self.func(s, i, words|{s[idx:i]}))
max_result = max(max_result, len(words|{s[idx:]}))
return max_result
def maxUniqueSplit(self, s: str) -> int:
return self.func(s, 0, set())
|
Given a string s, return the maximum number of unique substrings that the given string can be split into.
You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "ababccc"
Output: 5
Explanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.
Example 2:
Input: s = "aba"
Output: 2
Explanation: One way to split maximally is ['a', 'ba'].
Example 3:
Input: s = "aa"
Output: 1
Explanation: It is impossible to split the string any further.
Constraints:
1 <= s.length <= 16
s contains only lower case English letters.
|
class Solution:
def maxUniqueSplit(self, s: str) -> int:
#@functools.lru_cache(None)
def helper(start):
if len(s[start:]) == 0: return 0
res = -math.inf
for i in range(start+1,len(s)+1):
if s[start:i] not in seen:
seen.add(s[start:i])
#print('seen',seen)
followup = helper(i)
res= max(res,1+followup)
#print('results',results,followup,len(seen),seen)
seen.remove(s[start:i])
return res
seen = set()
return helper(0)
|
Given a string s, return the maximum number of unique substrings that the given string can be split into.
You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "ababccc"
Output: 5
Explanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.
Example 2:
Input: s = "aba"
Output: 2
Explanation: One way to split maximally is ['a', 'ba'].
Example 3:
Input: s = "aa"
Output: 1
Explanation: It is impossible to split the string any further.
Constraints:
1 <= s.length <= 16
s contains only lower case English letters.
|
class Solution:
splits = set()
def maxUniqueSplit(self, s: str) -> int:
n = len(s)
result = 0
for i in range(1, n + 1):
current = s[:i]
if current not in self.splits:
self.splits.add(current)
result = max(result, 1 + self.maxUniqueSplit(s[i:]))
self.splits.remove(current)
return result
|
Given a string s, return the maximum number of unique substrings that the given string can be split into.
You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "ababccc"
Output: 5
Explanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.
Example 2:
Input: s = "aba"
Output: 2
Explanation: One way to split maximally is ['a', 'ba'].
Example 3:
Input: s = "aa"
Output: 1
Explanation: It is impossible to split the string any further.
Constraints:
1 <= s.length <= 16
s contains only lower case English letters.
|
class Solution:
def maxUniqueSplit(self, s: str) -> int:
if not s:
return 0
splits = [[] for _ in range(len(s))]
best_len = 0
for i, c in enumerate(s):
splits[i].append(set([s[:i + 1]]))
best_len = max(best_len, 1)
for j in range(1, i + 1):
ss = s[j: i + 1]
for spl in splits[j - 1]:
if ss not in spl:
best_len = max(best_len, len(spl) + 1)
splits[i].append(spl | set([ss]))
return best_len
|
Given a string s, return the maximum number of unique substrings that the given string can be split into.
You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "ababccc"
Output: 5
Explanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.
Example 2:
Input: s = "aba"
Output: 2
Explanation: One way to split maximally is ['a', 'ba'].
Example 3:
Input: s = "aa"
Output: 1
Explanation: It is impossible to split the string any further.
Constraints:
1 <= s.length <= 16
s contains only lower case English letters.
|
class Solution:
def maxUniqueSplit(self, s: str) -> int:
def rec(i, myset):
if i == len(s):
return 0
ans = -float('inf')
for j in range(i, len(s)):
if s[i:j + 1] not in myset:
ans = max(ans, 1 + rec(j + 1, myset | set([s[i:j + 1]])))
return ans
return rec(0, set())
|
Given a string s, return the maximum number of unique substrings that the given string can be split into.
You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "ababccc"
Output: 5
Explanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.
Example 2:
Input: s = "aba"
Output: 2
Explanation: One way to split maximally is ['a', 'ba'].
Example 3:
Input: s = "aa"
Output: 1
Explanation: It is impossible to split the string any further.
Constraints:
1 <= s.length <= 16
s contains only lower case English letters.
|
class Solution:
def maxUniqueSplit(self, s: str) -> int:
best_ans = 1
cur_ans = set()
def find_result(i):
nonlocal best_ans
if i >= len(s):
return len(cur_ans)
elif len(s) - i + len(cur_ans) < best_ans:
return best_ans
for j in range(i+1, len(s)+1):
substr = s[i:j]
if substr not in cur_ans:
cur_ans.add(substr)
best_ans = max(best_ans, find_result(j))
cur_ans.remove(substr)
return max(best_ans, len(cur_ans))
return find_result(0)
|
Given a string s, return the maximum number of unique substrings that the given string can be split into.
You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "ababccc"
Output: 5
Explanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.
Example 2:
Input: s = "aba"
Output: 2
Explanation: One way to split maximally is ['a', 'ba'].
Example 3:
Input: s = "aa"
Output: 1
Explanation: It is impossible to split the string any further.
Constraints:
1 <= s.length <= 16
s contains only lower case English letters.
|
class Solution:
def maxUniqueSplit(self, s: str) -> int:
lookup = set()
return self.traverse(s, 0, lookup)
def traverse(self, s, index, lookup):
if index > len(s):
return 0
array = []
for idx in range(index,len(s)+1):
if len(s[index:idx])> 0 and s[index:idx] not in lookup:
lookup.add(s[index:idx])
array.append(1 + self.traverse(s, idx, lookup))
lookup.remove(s[index:idx])
return max(array) if array else 0
|
Given a string s, return the maximum number of unique substrings that the given string can be split into.
You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "ababccc"
Output: 5
Explanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.
Example 2:
Input: s = "aba"
Output: 2
Explanation: One way to split maximally is ['a', 'ba'].
Example 3:
Input: s = "aa"
Output: 1
Explanation: It is impossible to split the string any further.
Constraints:
1 <= s.length <= 16
s contains only lower case English letters.
|
class Solution:
def maxUniqueSplit(self, s: str) -> int:
def bitsoncount(x):
return bin(x).count('1')
ans = 0
n = len(s)
seen = defaultdict(int)
for m in range(1<<n):
if (bitsoncount(m) <= ans):
continue
prev = 0
count = 0
for i in range(n):
if m & (1<<i):
sub = s[prev:i+1]
prev = i+1
if sub not in seen:
seen[sub] += 1
count += 1
ans = max(ans, count)
seen.clear()
return ans
|
Given a string s, return the maximum number of unique substrings that the given string can be split into.
You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "ababccc"
Output: 5
Explanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.
Example 2:
Input: s = "aba"
Output: 2
Explanation: One way to split maximally is ['a', 'ba'].
Example 3:
Input: s = "aa"
Output: 1
Explanation: It is impossible to split the string any further.
Constraints:
1 <= s.length <= 16
s contains only lower case English letters.
|
class Solution:
def maxUniqueSplit(self, s: str) -> int:
result = []
def dfs(path, word):
if not word:
result.append(path)
return
for i in range(1, len(word)+1):
prefix, suffix = word[:i], word[i:]
if prefix not in path:
dfs(path | {prefix}, suffix)
dfs(set(), s)
l = 1
for item in result:
l = max(len(item), l)
return l
|
Given a string s, return the maximum number of unique substrings that the given string can be split into.
You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "ababccc"
Output: 5
Explanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.
Example 2:
Input: s = "aba"
Output: 2
Explanation: One way to split maximally is ['a', 'ba'].
Example 3:
Input: s = "aa"
Output: 1
Explanation: It is impossible to split the string any further.
Constraints:
1 <= s.length <= 16
s contains only lower case English letters.
|
class Solution:
def maxUniqueSplit(self, s: str) -> int:
n = len(s)
def dp(cur, ss):
if cur == n-1:
return len(set(ss.split()))
cur += 1
return max(dp(cur, ss + s[cur]), dp(cur, ss + ' ' + s[cur]))
return dp(0, s[0])
|
Given a string s, return the maximum number of unique substrings that the given string can be split into.
You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "ababccc"
Output: 5
Explanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.
Example 2:
Input: s = "aba"
Output: 2
Explanation: One way to split maximally is ['a', 'ba'].
Example 3:
Input: s = "aa"
Output: 1
Explanation: It is impossible to split the string any further.
Constraints:
1 <= s.length <= 16
s contains only lower case English letters.
|
class Solution:
def maxUniqueSplit(self, s: str) -> int:
used = set()
self.res = 1
self.backtrack(s, 0, used)
return self.res
def backtrack(self, s, cur, used):
if not s:
self.res = max(self.res, cur)
return
for i in range(1, len(s)+1):
if s[:i] not in used:
used.add(s[:i])
self.backtrack(s[i:], cur+1, used)
used.remove(s[:i])
|
Given a string s, return the maximum number of unique substrings that the given string can be split into.
You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "ababccc"
Output: 5
Explanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.
Example 2:
Input: s = "aba"
Output: 2
Explanation: One way to split maximally is ['a', 'ba'].
Example 3:
Input: s = "aa"
Output: 1
Explanation: It is impossible to split the string any further.
Constraints:
1 <= s.length <= 16
s contains only lower case English letters.
|
class Solution:
def maxUniqueSplit(self, s: str) -> int:
n = len(s)
self.res = 0
def dfs(strs, s):
if not s:
if len(set(strs)) == len(strs):
self.res = max(self.res, len(strs))
return
dfs(strs + [s[0]], s[1:])
if strs:
dfs(strs[:-1] + [strs[-1] + s[:1]], s[1:])
return
dfs([], s)
return self.res
|
Given a string s, return the maximum number of unique substrings that the given string can be split into.
You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "ababccc"
Output: 5
Explanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.
Example 2:
Input: s = "aba"
Output: 2
Explanation: One way to split maximally is ['a', 'ba'].
Example 3:
Input: s = "aa"
Output: 1
Explanation: It is impossible to split the string any further.
Constraints:
1 <= s.length <= 16
s contains only lower case English letters.
|
class Solution:
def maxUniqueSplit(self, s: str) -> int:
def helper(s, seen=set()):
maximum = 0
for i in range(1, len(s) + 1):
candidate = s[:i]
if candidate not in seen:
maximum = max(maximum, 1 + helper(s[i:], {candidate, *seen}))
return maximum
return helper(s)
|
Given a string s, return the maximum number of unique substrings that the given string can be split into.
You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "ababccc"
Output: 5
Explanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.
Example 2:
Input: s = "aba"
Output: 2
Explanation: One way to split maximally is ['a', 'ba'].
Example 3:
Input: s = "aa"
Output: 1
Explanation: It is impossible to split the string any further.
Constraints:
1 <= s.length <= 16
s contains only lower case English letters.
|
# 1593. Split a String Into the max Number of Unique Substrings
def walk_divisions (string, covered, cut):
if cut == len (string):
yield len (covered)
else:
for nxt in range (cut + 1, len (string) + 1):
substring = string[cut : nxt]
if substring not in covered:
covered.append (substring)
yield from walk_divisions (string, covered, nxt)
covered.pop ()
def max_unique_split (string):
if len (string) == 1:
return 1
assert len (string) >= 2
return max (walk_divisions (string, [], 0))
class Solution:
def maxUniqueSplit(self, s: str) -> int:
return max_unique_split(s)
|
Given a string s, return the maximum number of unique substrings that the given string can be split into.
You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "ababccc"
Output: 5
Explanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.
Example 2:
Input: s = "aba"
Output: 2
Explanation: One way to split maximally is ['a', 'ba'].
Example 3:
Input: s = "aa"
Output: 1
Explanation: It is impossible to split the string any further.
Constraints:
1 <= s.length <= 16
s contains only lower case English letters.
|
class Solution:
def maxUniqueSplit(self, s: str) -> int:
n = len(s)
def dp(i, cur):
nonlocal ans
if len(cur) + n-i < ans: return
if i >= n: ans = max(ans, len(cur))
l = n-i
for k in range(1, l+1):
if s[i:i+k] not in cur:
cur.append(s[i:i+k])
dp(i+k, cur)
cur.pop()
ans, cur = 0, []
dp(0, cur)
return ans
|
Given a string s, return the maximum number of unique substrings that the given string can be split into.
You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "ababccc"
Output: 5
Explanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.
Example 2:
Input: s = "aba"
Output: 2
Explanation: One way to split maximally is ['a', 'ba'].
Example 3:
Input: s = "aa"
Output: 1
Explanation: It is impossible to split the string any further.
Constraints:
1 <= s.length <= 16
s contains only lower case English letters.
|
class Solution:
def maxUniqueSplit(self, s: str) -> int:
prev = [[s[0]]]
for elm in s[1:]:
current = []
for sub in prev:
copy = list(sub)
copy[-1] = copy[-1] + elm
current.append(copy)
copy = list(sub)
copy.append(elm)
current.append(copy)
prev = current
return max(len(set(combo)) for combo in prev)
|
Given a string s, return the maximum number of unique substrings that the given string can be split into.
You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "ababccc"
Output: 5
Explanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.
Example 2:
Input: s = "aba"
Output: 2
Explanation: One way to split maximally is ['a', 'ba'].
Example 3:
Input: s = "aa"
Output: 1
Explanation: It is impossible to split the string any further.
Constraints:
1 <= s.length <= 16
s contains only lower case English letters.
|
class Solution:
def maxUniqueSplit(self, s: str, seen=()):
maximum = 0
if s:
for i in range(1, len(s) + 1):
candidate = s[:i]
if candidate not in seen:
maximum = max(maximum, 1 + Solution.maxUniqueSplit(self, s[i:], {candidate, *seen}))
return maximum
|
Given a string s, return the maximum number of unique substrings that the given string can be split into.
You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "ababccc"
Output: 5
Explanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.
Example 2:
Input: s = "aba"
Output: 2
Explanation: One way to split maximally is ['a', 'ba'].
Example 3:
Input: s = "aa"
Output: 1
Explanation: It is impossible to split the string any further.
Constraints:
1 <= s.length <= 16
s contains only lower case English letters.
|
class Solution:
def maxUniqueSplit(self, s: str) -> int:
self.maxsplits = 0
def DFS(i, substring_set):
if i == len(s):
self.maxsplits = max(len(substring_set), self.maxsplits)
return
for j in range(i + 1, len(s) + 1):
DFS(j, substring_set | {s[i: j]})
DFS(0, set())
return self.maxsplits
|
Given a string s, return the maximum number of unique substrings that the given string can be split into.
You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "ababccc"
Output: 5
Explanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.
Example 2:
Input: s = "aba"
Output: 2
Explanation: One way to split maximally is ['a', 'ba'].
Example 3:
Input: s = "aa"
Output: 1
Explanation: It is impossible to split the string any further.
Constraints:
1 <= s.length <= 16
s contains only lower case English letters.
|
class Solution:
def maxUniqueSplit(self, s: str) -> int:
have = set()
self.cur = []
def dfs(i):
if i == len(s):
return 0 if ''.join(self.cur) not in have else -float('inf')
self.cur.append(s[i])
ret = dfs(i + 1)
st = ''.join(self.cur)
if st not in have:
tmp, self.cur = self.cur, []
have.add(st)
ret = max(dfs(i + 1) + 1, ret)
have.remove(st)
self.cur = tmp
self.cur.pop()
return ret
return dfs(0)
|
Given a string s, return the maximum number of unique substrings that the given string can be split into.
You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "ababccc"
Output: 5
Explanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.
Example 2:
Input: s = "aba"
Output: 2
Explanation: One way to split maximally is ['a', 'ba'].
Example 3:
Input: s = "aa"
Output: 1
Explanation: It is impossible to split the string any further.
Constraints:
1 <= s.length <= 16
s contains only lower case English letters.
|
class Solution:
def maxUniqueSplit(self, s: str) -> int:
self.seen = set()
self.result = 0
def backtrack(s, start):
if start == len(s):
return True
for end in range(start + 1, len(s) + 1):
if s[start:end] not in self.seen:
self.seen.add(s[start:end])
if backtrack(s, end):
self.result = max(self.result, len(self.seen))
self.seen.remove(s[start:end])
return False
backtrack(s, 0)
return self.result
|
Given a string s, return the maximum number of unique substrings that the given string can be split into.
You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "ababccc"
Output: 5
Explanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.
Example 2:
Input: s = "aba"
Output: 2
Explanation: One way to split maximally is ['a', 'ba'].
Example 3:
Input: s = "aa"
Output: 1
Explanation: It is impossible to split the string any further.
Constraints:
1 <= s.length <= 16
s contains only lower case English letters.
|
class Solution:
def maxUniqueSplit(self, s: str) -> int:
exist = collections.defaultdict(int)
self.result = 0
n = len(s)
def dfs(index:int) -> None:
# print(exist, index)
if (index == n):
self.result = max(self.result, len(exist))
return
for i in range(index + 1, n + 1):
st = s[index:i]
exist[st] += 1
dfs(i)
exist[st] -= 1
if (exist[st] == 0):
del exist[st]
dfs(0)
return self.result
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.