inputs
stringlengths 50
14k
| targets
stringlengths 4
655k
|
|---|---|
Return the number of distinct non-empty substrings of text that can be written as the concatenation of some string with itself (i.e. it can be written as a + a where a is some string).
Example 1:
Input: text = "abcabcabc"
Output: 3
Explanation: The 3 substrings are "abcabc", "bcabca" and "cabcab".
Example 2:
Input: text = "leetcodeleetcode"
Output: 2
Explanation: The 2 substrings are "ee" and "leetcodeleetcode".
Constraints:
1 <= text.length <= 2000
text has only lowercase English letters.
|
class Solution:
def distinctEchoSubstrings(self, text: str) -> int:
count = 0
visited = {}
for i in range(len(text)):
for length in range(1, len(text)//2+1):
now = text[i:i+length]
if now in visited:
continue
if now == text[i+length:i + 2*length]:
count += 1
visited[now] = 1
return count
|
Return the number of distinct non-empty substrings of text that can be written as the concatenation of some string with itself (i.e. it can be written as a + a where a is some string).
Example 1:
Input: text = "abcabcabc"
Output: 3
Explanation: The 3 substrings are "abcabc", "bcabca" and "cabcab".
Example 2:
Input: text = "leetcodeleetcode"
Output: 2
Explanation: The 2 substrings are "ee" and "leetcodeleetcode".
Constraints:
1 <= text.length <= 2000
text has only lowercase English letters.
|
class Solution:
def distinctEchoSubstrings(self, text: str) -> int:
seen = set()
count = 0
for i in range(len(text)-1):
for j in range(i, len(text), 1):
l=(j-i+1)//2
if l<1: continue
h=l+i
t = text[i:h+l]
# print(text[i:h], text[h:h+l], i, j)
if t in seen: continue
if t[:l] == t[l:]:
count += 1
# print( '**', text[i:h+l])
seen.add(t)
return count
|
Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.
Example:
nums = [1, 2, 3]
target = 4
The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
Note that different sequences are counted as different combinations.
Therefore the output is 7.
Follow up:
What if negative numbers are allowed in the given array?
How does it change the problem?
What limitation we need to add to the question to allow negative numbers?
Credits:Special thanks to @pbrother for adding this problem and creating all test cases.
|
class Solution:
def combinationSum4(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
cache = {}
def f(val):
if val == target:
return 1
total = 0
remain = target - val
for num in nums:
if num <= remain:
k = val+num
if k in cache:
total += cache[k]
else:
cache[k] = f(val + num)
total += cache[k]
return total
return f(0)
|
Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.
Example:
nums = [1, 2, 3]
target = 4
The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
Note that different sequences are counted as different combinations.
Therefore the output is 7.
Follow up:
What if negative numbers are allowed in the given array?
How does it change the problem?
What limitation we need to add to the question to allow negative numbers?
Credits:Special thanks to @pbrother for adding this problem and creating all test cases.
|
class Solution:
def combinationSum4(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
record={0:1}
def helper(target):
if target in record:
return record[target]
res=0
for x in nums:
if target>=x:
res+=helper(target-x)
record[target]=res
return res
return helper(target)
|
Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.
Example:
nums = [1, 2, 3]
target = 4
The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
Note that different sequences are counted as different combinations.
Therefore the output is 7.
Follow up:
What if negative numbers are allowed in the given array?
How does it change the problem?
What limitation we need to add to the question to allow negative numbers?
Credits:Special thanks to @pbrother for adding this problem and creating all test cases.
|
class Solution(object):
def combinationSum4(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
dp = [0] + [-1] * target
def calc(target):
if target == 0:
return 1
if dp[target] >= 0:
return dp[target]
count = 0
for n in nums:
if target - n >= 0:
tmp = calc(target - n)
if tmp >= 0:
count += tmp
dp[target] = count
return count
ans = calc(target)
print(ans)
print(dp)
return ans
|
Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.
Example:
nums = [1, 2, 3]
target = 4
The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
Note that different sequences are counted as different combinations.
Therefore the output is 7.
Follow up:
What if negative numbers are allowed in the given array?
How does it change the problem?
What limitation we need to add to the question to allow negative numbers?
Credits:Special thanks to @pbrother for adding this problem and creating all test cases.
|
class Solution:
# recursive, time limit exceeded
def combinationSum4_1(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
res = 0
if target == 0:
return 1
for i in range(len(nums)):
if target >= nums[i]:
res += self.combinationSum4(nums, target - nums[i])
return res
# top down using memory
def combinationSum4_2(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
dp = [-1] * (target + 1)
dp[0] = 1
return self.helper(dp, nums, target)
def helper(self, dp, nums, target):
if dp[target] != -1:
return dp[target]
res = 0
for i in range(len(nums)):
if target >= nums[i]:
res += self.helper(dp, nums, target - nums[i])
dp[target] = res
return res
# bottom up
def combinationSum4(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
dp = [0] * (target + 1)
dp[0] = 1
for i in range(target + 1):
for num in sorted(nums):
if i < num: break
dp[i] += dp[i - num]
return dp[-1]
|
Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.
Example:
nums = [1, 2, 3]
target = 4
The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
Note that different sequences are counted as different combinations.
Therefore the output is 7.
Follow up:
What if negative numbers are allowed in the given array?
How does it change the problem?
What limitation we need to add to the question to allow negative numbers?
Credits:Special thanks to @pbrother for adding this problem and creating all test cases.
|
class Solution:
def combinationSum4(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
dp = [0 for x in range(target+1)]
dp[0] = 1
for x in range(1, target+1):
for elem in nums:
if x >= elem:
dp[x]+=dp[x - elem]
return dp[-1]
|
Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.
Example:
nums = [1, 2, 3]
target = 4
The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
Note that different sequences are counted as different combinations.
Therefore the output is 7.
Follow up:
What if negative numbers are allowed in the given array?
How does it change the problem?
What limitation we need to add to the question to allow negative numbers?
Credits:Special thanks to @pbrother for adding this problem and creating all test cases.
|
class Solution:
def combinationSum4(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
dp = [0]*(target + 1)
dp[0] = 1
for i in range(1, target+1):
for num in nums:
if num>i:
break
dp[i]+=dp[i-num]
return dp[target]
|
Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.
Example:
nums = [1, 2, 3]
target = 4
The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
Note that different sequences are counted as different combinations.
Therefore the output is 7.
Follow up:
What if negative numbers are allowed in the given array?
How does it change the problem?
What limitation we need to add to the question to allow negative numbers?
Credits:Special thanks to @pbrother for adding this problem and creating all test cases.
|
class Solution:
# recursive, time limit exceeded
def combinationSum4_1(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
res = 0
if target == 0:
return 1
for i in range(len(nums)):
if target >= nums[i]:
res += self.combinationSum4(nums, target - nums[i])
return res
# top down using memory
def combinationSum4_2(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
dp = [-1] * (target + 1)
dp[0] = 1
return self.helper(dp, nums, target)
def helper(self, dp, nums, target):
if dp[target] != -1:
return dp[target]
res = 0
for i in range(len(nums)):
if target >= nums[i]:
res += self.helper(dp, nums, target - nums[i])
dp[target] = res
return res
# bottom up
def combinationSum4(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
dp = [0] * (target + 1)
dp[0] = 1
for i in range(target + 1):
for num in sorted(nums):
if i < num: break
dp[i] += dp[i - num]
return dp[-1]
|
Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.
Example:
nums = [1, 2, 3]
target = 4
The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
Note that different sequences are counted as different combinations.
Therefore the output is 7.
Follow up:
What if negative numbers are allowed in the given array?
How does it change the problem?
What limitation we need to add to the question to allow negative numbers?
Credits:Special thanks to @pbrother for adding this problem and creating all test cases.
|
class Solution:
# recursive, time limit exceeded
def combinationSum4_1(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
res = 0
if target == 0:
return 1
for i in range(len(nums)):
if target >= nums[i]:
res += self.combinationSum4(nums, target - nums[i])
return res
# top down using memory
def combinationSum4_2(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
dp = [-1] * (target + 1)
dp[0] = 1
return self.helper(dp, nums, target)
def helper(self, dp, nums, target):
if dp[target] != -1:
return dp[target]
res = 0
for i in range(len(nums)):
if target >= nums[i]:
res += self.helper(dp, nums, target - nums[i])
dp[target] = res
return res
# bottom up
def combinationSum4(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
dp = [0] * (target + 1)
dp[0] = 1
for i in range(target + 1):
for j in range(len(nums)):
if i - nums[j] >= 0:
dp[i] += dp[i - nums[j]]
return dp[-1]
|
Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.
Example:
nums = [1, 2, 3]
target = 4
The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
Note that different sequences are counted as different combinations.
Therefore the output is 7.
Follow up:
What if negative numbers are allowed in the given array?
How does it change the problem?
What limitation we need to add to the question to allow negative numbers?
Credits:Special thanks to @pbrother for adding this problem and creating all test cases.
|
class Solution:
def combinationSum4(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
def dfs(nums,target,memo):
if target in memo:
return memo[target]
if target < 0:
return
if target == 0:
memo[target] = 1
return
memo[target] = 0
for num in nums:
dfs(nums, target-num,memo)
if target-num >= 0:
memo[target] += memo[target-num]
dfs.count = 0
nums.sort()
memo = {}
dfs(nums,target,memo)
return memo[target]
|
Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.
Example:
nums = [1, 2, 3]
target = 4
The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
Note that different sequences are counted as different combinations.
Therefore the output is 7.
Follow up:
What if negative numbers are allowed in the given array?
How does it change the problem?
What limitation we need to add to the question to allow negative numbers?
Credits:Special thanks to @pbrother for adding this problem and creating all test cases.
|
class Solution:
def combinationSum4(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
self.dp = [-1]*(target+1)
self.dp[0] = 1
return self.cSUtil(nums, target)
def cSUtil(self, nums, target):
if target < 0:
return 0
if self.dp[target] != -1:
return self.dp[target]
res = 0
for num in nums:
target -= num
res += self.cSUtil(nums, target)
target += num
self.dp[target] = res
return res
|
Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.
Example:
nums = [1, 2, 3]
target = 4
The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
Note that different sequences are counted as different combinations.
Therefore the output is 7.
Follow up:
What if negative numbers are allowed in the given array?
How does it change the problem?
What limitation we need to add to the question to allow negative numbers?
Credits:Special thanks to @pbrother for adding this problem and creating all test cases.
|
class Solution:
def combinationSum4(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
return self.use_dp(nums, target)
def use_dfs(self, nums, target):
self.result = 0
nums.sort()
self.dfs(nums, target)
return self.result
def dfs(self, nums, target):
if target == 0:
self.result += 1
return
for num in nums:
if num > target:
break
self.dfs(nums, target - num)
def use_recursion_dp(self, nums, target):
dp = [-1] * (target + 1)
dp[0] = 1
nums.sort()
return self.dp_dfs(nums, target, dp)
def dp_dfs(self, nums, target, dp):
if dp[target] != -1:
return dp[target]
result = 0
for num in nums:
if num > target:
break
result += self.dp_dfs(nums, target - num, dp)
dp[target] = result
return result
def use_dp(self, nums, target):
dp = [0] * (target + 1)
dp[0] = 1
for item in range(1, len(dp)):
for num in nums:
if item - num >= 0:
dp[item] += dp[item - num]
return dp[target]
|
Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.
Example:
nums = [1, 2, 3]
target = 4
The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
Note that different sequences are counted as different combinations.
Therefore the output is 7.
Follow up:
What if negative numbers are allowed in the given array?
How does it change the problem?
What limitation we need to add to the question to allow negative numbers?
Credits:Special thanks to @pbrother for adding this problem and creating all test cases.
|
class Solution:
def combinationSum4(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if not nums:
return 0
n_nums = len(nums)
# combinations = [[0]*(n_nums+1)]*(target+max(nums)+3)
combinations = [[0]*(n_nums+1) for i in range(target+max(nums)+3)]
for i in range(1, target + 1):
cur_sum = 0
for j in range(n_nums):
if i == nums[j]:
combinations[i][j] = 1
else:
combinations[i][j] = combinations[i - nums[j]][n_nums]
cur_sum += combinations[i][j]
combinations[i][n_nums]= cur_sum
return combinations[target][n_nums]
|
Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.
Example:
nums = [1, 2, 3]
target = 4
The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
Note that different sequences are counted as different combinations.
Therefore the output is 7.
Follow up:
What if negative numbers are allowed in the given array?
How does it change the problem?
What limitation we need to add to the question to allow negative numbers?
Credits:Special thanks to @pbrother for adding this problem and creating all test cases.
|
class Solution:
count = 0
def combinationSum4(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
comb = [0]*(target + 1)
comb[0] = 1
for i in range(1, len(comb)):
for j in range(0, len(nums)):
if i - nums[j] >= 0:
comb[i] += comb[i - nums[j]]
return comb[target]
# self.helper(nums, 0, target, 0)
# return self.count
# def helper(self, nums, i, target, Sum):
# if i >= len(nums) or Sum > target:
# return
# if Sum == target:
# self.count += 1
# return
# for j in range(0, len(nums)):
# self.helper(nums, j, target, Sum + nums[j])
|
There are two types of soup: type A and type B. Initially we have N ml of each type of soup. There are four kinds of operations:
Serve 100 ml of soup A and 0 ml of soup B
Serve 75 ml of soup A and 25 ml of soup B
Serve 50 ml of soup A and 50 ml of soup B
Serve 25 ml of soup A and 75 ml of soup B
When we serve some soup, we give it to someone and we no longer have it. Each turn, we will choose from the four operations with equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as we can. We stop once we no longer have some quantity of both types of soup.
Note that we do not have the operation where all 100 ml's of soup B are used first.
Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time.
Example:
Input: N = 50
Output: 0.625
Explanation:
If we choose the first two operations, A will become empty first. For the third operation, A and B will become empty at the same time. For the fourth operation, B will become empty first. So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.
Notes:
0 <= N <= 10^9.
Answers within 10^-6 of the true value will be accepted as correct.
|
class Solution:
def soupServings(self, N: int) -> float:
if N > 5000: return 1 # shortcut for large N (accurate to 1e-6)
@lru_cache(None)
def dp(a, b):
if a <= 0 and b <= 0: return 0.5
if a <= 0: return 1
if b <= 0: return 0
return (dp(a-100, b) + dp(a-75, b-25) + dp(a-50, b-50) + dp(a-25, b-75)) / 4
return dp(N, N)
|
There are two types of soup: type A and type B. Initially we have N ml of each type of soup. There are four kinds of operations:
Serve 100 ml of soup A and 0 ml of soup B
Serve 75 ml of soup A and 25 ml of soup B
Serve 50 ml of soup A and 50 ml of soup B
Serve 25 ml of soup A and 75 ml of soup B
When we serve some soup, we give it to someone and we no longer have it. Each turn, we will choose from the four operations with equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as we can. We stop once we no longer have some quantity of both types of soup.
Note that we do not have the operation where all 100 ml's of soup B are used first.
Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time.
Example:
Input: N = 50
Output: 0.625
Explanation:
If we choose the first two operations, A will become empty first. For the third operation, A and B will become empty at the same time. For the fourth operation, B will become empty first. So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.
Notes:
0 <= N <= 10^9.
Answers within 10^-6 of the true value will be accepted as correct.
|
class Solution:
mem={}
def soupServings(self, N: int) -> float:
if N>4800:
return 1
def empty(a,b):
if (a,b) in self.mem:
return self.mem[(a,b)]
if a<=0 and b<=0:
return 0.5
if a<=0:
return 1
if b<=0:
return 0
ans=0.25*(empty(a-4,b)+empty(a-3,b-1)+empty(a-2,b-2)+empty(a-1,b-3))
self.mem[(a,b)]=ans
return ans
N=math.ceil(N/25)
return empty(N,N)
|
There are two types of soup: type A and type B. Initially we have N ml of each type of soup. There are four kinds of operations:
Serve 100 ml of soup A and 0 ml of soup B
Serve 75 ml of soup A and 25 ml of soup B
Serve 50 ml of soup A and 50 ml of soup B
Serve 25 ml of soup A and 75 ml of soup B
When we serve some soup, we give it to someone and we no longer have it. Each turn, we will choose from the four operations with equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as we can. We stop once we no longer have some quantity of both types of soup.
Note that we do not have the operation where all 100 ml's of soup B are used first.
Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time.
Example:
Input: N = 50
Output: 0.625
Explanation:
If we choose the first two operations, A will become empty first. For the third operation, A and B will become empty at the same time. For the fourth operation, B will become empty first. So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.
Notes:
0 <= N <= 10^9.
Answers within 10^-6 of the true value will be accepted as correct.
|
class Solution:
def soupServings(self, N: int) -> float:
seen={}
def find_prob(A,B):
if A==0 and B==0:
return 0.5
if A==0:
return 1
if B==0:
return 0
if (A,B) in seen:
return seen[A,B]
temp=0
for x,y in [[100,0],[75,25],[50,50],[25,75]]:
temp+=find_prob(A-x if A>x else 0,B-y if B>y else 0)
seen[A,B]=0.25*temp
return 0.25*temp
if N>4800: return 1.0
return find_prob(N,N)
|
There are two types of soup: type A and type B. Initially we have N ml of each type of soup. There are four kinds of operations:
Serve 100 ml of soup A and 0 ml of soup B
Serve 75 ml of soup A and 25 ml of soup B
Serve 50 ml of soup A and 50 ml of soup B
Serve 25 ml of soup A and 75 ml of soup B
When we serve some soup, we give it to someone and we no longer have it. Each turn, we will choose from the four operations with equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as we can. We stop once we no longer have some quantity of both types of soup.
Note that we do not have the operation where all 100 ml's of soup B are used first.
Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time.
Example:
Input: N = 50
Output: 0.625
Explanation:
If we choose the first two operations, A will become empty first. For the third operation, A and B will become empty at the same time. For the fourth operation, B will become empty first. So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.
Notes:
0 <= N <= 10^9.
Answers within 10^-6 of the true value will be accepted as correct.
|
class Solution:
def soupServings(self, N: int) -> float:
def f(a,b):
if a <= 0 and b <= 0:
return 0.5
if a <= 0:
return 1
if b <= 0:
return 0
if _memo[a][b] >0:
return _memo[a][b]
_memo[a][b] = 0.25 *(f(a - 4,b) + f(a - 3,b - 1) + f(a - 2,b - 2) + f(a - 1,b - 3) )
return _memo[a][b]
_memo = [[0] * 200 for i in range(200)]
if N >= 4800:
return 1
else:
return f((N + 24) // 25, (N + 24) // 25)
|
There are two types of soup: type A and type B. Initially we have N ml of each type of soup. There are four kinds of operations:
Serve 100 ml of soup A and 0 ml of soup B
Serve 75 ml of soup A and 25 ml of soup B
Serve 50 ml of soup A and 50 ml of soup B
Serve 25 ml of soup A and 75 ml of soup B
When we serve some soup, we give it to someone and we no longer have it. Each turn, we will choose from the four operations with equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as we can. We stop once we no longer have some quantity of both types of soup.
Note that we do not have the operation where all 100 ml's of soup B are used first.
Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time.
Example:
Input: N = 50
Output: 0.625
Explanation:
If we choose the first two operations, A will become empty first. For the third operation, A and B will become empty at the same time. For the fourth operation, B will become empty first. So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.
Notes:
0 <= N <= 10^9.
Answers within 10^-6 of the true value will be accepted as correct.
|
class Solution:
def soupServings(self, N: int) -> float:
q, r = divmod(N, 25)
N = q + (r > 0)
if N >= 500:
return 1
memo = {}
def dp(x, y):
if (x, y) not in memo:
if x <= 0 or y <= 0:
res = 0.5 if x <= 0 and y <= 0 else 1.0 if x <= 0 else 0.0
else:
res = 0.25 * (dp(x-4, y) + dp(x-3, y-1) + dp(x-2, y-2) + dp(x-1, y-3))
memo[x, y] = res
return memo[x, y]
return dp(N, N)
|
There are two types of soup: type A and type B. Initially we have N ml of each type of soup. There are four kinds of operations:
Serve 100 ml of soup A and 0 ml of soup B
Serve 75 ml of soup A and 25 ml of soup B
Serve 50 ml of soup A and 50 ml of soup B
Serve 25 ml of soup A and 75 ml of soup B
When we serve some soup, we give it to someone and we no longer have it. Each turn, we will choose from the four operations with equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as we can. We stop once we no longer have some quantity of both types of soup.
Note that we do not have the operation where all 100 ml's of soup B are used first.
Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time.
Example:
Input: N = 50
Output: 0.625
Explanation:
If we choose the first two operations, A will become empty first. For the third operation, A and B will become empty at the same time. For the fourth operation, B will become empty first. So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.
Notes:
0 <= N <= 10^9.
Answers within 10^-6 of the true value will be accepted as correct.
|
class Solution:
def soupServings(self, N: int) -> float:
if N > 10000:
return 1
rounds = (N + 25 - 1) // 25
dp = [{(N, N): 1}] + [collections.defaultdict(float) for _ in range(rounds)]
for i in range(1, rounds + 1):
for a, b in dp[i-1]:
if a <= 0 or b <= 0:
dp[i][a, b] += dp[i-1][a, b]
else:
dp[i][max(a-100, 0), b] += dp[i-1][a, b] * 0.25
dp[i][max(a-75, 0), max(b-25, 0)] += dp[i-1][a, b] * 0.25
dp[i][max(a-50, 0), max(b-50, 0)] += dp[i-1][a, b] * 0.25
dp[i][max(a-25, 0), max(b-75, 0)] += dp[i-1][a, b] * 0.25
res = dp[rounds][0, 0] / 2
for a, b in dp[rounds]:
if a <= 0 and b > 0:
res += dp[rounds][a,b]
return res
|
There are two types of soup: type A and type B. Initially we have N ml of each type of soup. There are four kinds of operations:
Serve 100 ml of soup A and 0 ml of soup B
Serve 75 ml of soup A and 25 ml of soup B
Serve 50 ml of soup A and 50 ml of soup B
Serve 25 ml of soup A and 75 ml of soup B
When we serve some soup, we give it to someone and we no longer have it. Each turn, we will choose from the four operations with equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as we can. We stop once we no longer have some quantity of both types of soup.
Note that we do not have the operation where all 100 ml's of soup B are used first.
Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time.
Example:
Input: N = 50
Output: 0.625
Explanation:
If we choose the first two operations, A will become empty first. For the third operation, A and B will become empty at the same time. For the fourth operation, B will become empty first. So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.
Notes:
0 <= N <= 10^9.
Answers within 10^-6 of the true value will be accepted as correct.
|
#
class Solution:
def soupServings(self, N: int) -> float:
Q, R = divmod(N, 25)
N = Q + (R > 0)
if N >= 500: return 1
memo = {}
def dp(x, y):
if (x, y) not in memo:
if x <= 0 or y <= 0:
ans = 0.5 if x<=0 and y<=0 else 1.0 if x<=0 else 0.0
else:
ans = 0.25 * (dp(x-4,y)+dp(x-3,y-1)+dp(x-2,y-2)+dp(x-1,y-3))
memo[x, y] = ans
return memo[x, y]
return dp(N, N)
|
There are two types of soup: type A and type B. Initially we have N ml of each type of soup. There are four kinds of operations:
Serve 100 ml of soup A and 0 ml of soup B
Serve 75 ml of soup A and 25 ml of soup B
Serve 50 ml of soup A and 50 ml of soup B
Serve 25 ml of soup A and 75 ml of soup B
When we serve some soup, we give it to someone and we no longer have it. Each turn, we will choose from the four operations with equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as we can. We stop once we no longer have some quantity of both types of soup.
Note that we do not have the operation where all 100 ml's of soup B are used first.
Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time.
Example:
Input: N = 50
Output: 0.625
Explanation:
If we choose the first two operations, A will become empty first. For the third operation, A and B will become empty at the same time. For the fourth operation, B will become empty first. So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.
Notes:
0 <= N <= 10^9.
Answers within 10^-6 of the true value will be accepted as correct.
|
class Solution:
def soupServings(self, N: int) -> float:
# 4,0
# 3,1
# 2,2
# 1,3
if N % 25 == 0:
N = N // 25
else:
N = (N // 25) + 1
solA = {}
solB = {}
def solutionA(a,b):
if a == 0 and b > 0:
return 1
elif a == 0 and b == 0:
return 0
elif a > 0 and b == 0:
return 0
else:
if (a,b) in solA:
return solA[(a,b)]
else:
solA[(a,b)] = 0.25 * (solutionA(max(a-4,0),b) + solutionA(max(a-3,0),max(b-1,0)) + solutionA(max(a-2,0),max(b-2,0)) + solutionA(max(a-1,0),max(b-3,0)))
return solA[(a,b)]
def solutionB(a,b):
if a == 0 and b == 0:
return 1
elif a == 0 or b == 0:
return 0
else:
if (a,b) in solB:
return solB[(a,b)]
else:
solB[(a,b)] = 0.25 * (solutionB(max(a-4,0),b) + solutionB(max(a-3,0),max(b-1,0)) + solutionB(max(a-2,0),max(b-2,0)) + solutionB(max(a-1,0),max(b-3,0)))
return solB[(a,b)]
if N > 300:
return 1
else:
return solutionA(N,N) + 0.5*solutionB(N,N)
|
There are two types of soup: type A and type B. Initially we have N ml of each type of soup. There are four kinds of operations:
Serve 100 ml of soup A and 0 ml of soup B
Serve 75 ml of soup A and 25 ml of soup B
Serve 50 ml of soup A and 50 ml of soup B
Serve 25 ml of soup A and 75 ml of soup B
When we serve some soup, we give it to someone and we no longer have it. Each turn, we will choose from the four operations with equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as we can. We stop once we no longer have some quantity of both types of soup.
Note that we do not have the operation where all 100 ml's of soup B are used first.
Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time.
Example:
Input: N = 50
Output: 0.625
Explanation:
If we choose the first two operations, A will become empty first. For the third operation, A and B will become empty at the same time. For the fourth operation, B will become empty first. So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.
Notes:
0 <= N <= 10^9.
Answers within 10^-6 of the true value will be accepted as correct.
|
class Solution:
def soupServings(self, N):
if N>=5551: return 1
self.dd=collections.defaultdict(float)
return self.sub(N,N)
def sub(self, an, bn):
if an<=0 and bn<=0: return 0.5
if an<=0: return 1
if bn<=0: return 0
if (an,bn) in self.dd: return self.dd[(an,bn)]
c1=self.sub(an-100, bn)
c2=self.sub(an-75, bn-25)
c3=self.sub(an-50, bn-50)
c4=self.sub(an-25, bn-75)
self.dd[(an,bn)]=0.25*sum([c1,c2,c3,c4])
return self.dd[(an,bn)]
|
There are two types of soup: type A and type B. Initially we have N ml of each type of soup. There are four kinds of operations:
Serve 100 ml of soup A and 0 ml of soup B
Serve 75 ml of soup A and 25 ml of soup B
Serve 50 ml of soup A and 50 ml of soup B
Serve 25 ml of soup A and 75 ml of soup B
When we serve some soup, we give it to someone and we no longer have it. Each turn, we will choose from the four operations with equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as we can. We stop once we no longer have some quantity of both types of soup.
Note that we do not have the operation where all 100 ml's of soup B are used first.
Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time.
Example:
Input: N = 50
Output: 0.625
Explanation:
If we choose the first two operations, A will become empty first. For the third operation, A and B will become empty at the same time. For the fourth operation, B will become empty first. So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.
Notes:
0 <= N <= 10^9.
Answers within 10^-6 of the true value will be accepted as correct.
|
import math
class Solution:
def soupServings(self, N: int) -> float:
N = math.ceil(N/25)
if N>=1000:
return 1
dp = [[1 for i in range(N+1)] for j in range(N+1)]
for i in range(0,N+1):
dp[i][0] = 0
dp[0][0] = 0.5
for i in range(1,N+1):
for j in range(1,N+1):
M = lambda x: max(0,x)
dp[i][j] = 0.25 * (dp[M(i - 4)][j] + dp[M(i -3)][j - 1]
+ dp[M(i - 2)][M(j - 2)] + dp[i - 1][M(j - 3)])
if(1 - dp[i][j] < 0.000001):
break
if(1 - dp[i][i] < 0.000001):
break
return dp[N][N]
|
There are two types of soup: type A and type B. Initially we have N ml of each type of soup. There are four kinds of operations:
Serve 100 ml of soup A and 0 ml of soup B
Serve 75 ml of soup A and 25 ml of soup B
Serve 50 ml of soup A and 50 ml of soup B
Serve 25 ml of soup A and 75 ml of soup B
When we serve some soup, we give it to someone and we no longer have it. Each turn, we will choose from the four operations with equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as we can. We stop once we no longer have some quantity of both types of soup.
Note that we do not have the operation where all 100 ml's of soup B are used first.
Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time.
Example:
Input: N = 50
Output: 0.625
Explanation:
If we choose the first two operations, A will become empty first. For the third operation, A and B will become empty at the same time. For the fourth operation, B will become empty first. So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.
Notes:
0 <= N <= 10^9.
Answers within 10^-6 of the true value will be accepted as correct.
|
class Solution:
def soupServings(self, N: int) -> float:
memo = {}
if N > 4800: return 1
def dp(a ,b):
if (a, b) in memo: return memo[a, b]
if a <= 0 and b > 0: return 1
if a <= 0 and b <= 0: return 0.5
if a > 0 and b <= 0: return 0
memo[a, b] = (dp(a - 100, b) + dp(a - 75, b - 25) + dp(a - 50, b - 50) + dp(a - 25, b - 75)) / 4
return memo[a, b]
return dp(N, N)
|
There are two types of soup: type A and type B. Initially we have N ml of each type of soup. There are four kinds of operations:
Serve 100 ml of soup A and 0 ml of soup B
Serve 75 ml of soup A and 25 ml of soup B
Serve 50 ml of soup A and 50 ml of soup B
Serve 25 ml of soup A and 75 ml of soup B
When we serve some soup, we give it to someone and we no longer have it. Each turn, we will choose from the four operations with equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as we can. We stop once we no longer have some quantity of both types of soup.
Note that we do not have the operation where all 100 ml's of soup B are used first.
Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time.
Example:
Input: N = 50
Output: 0.625
Explanation:
If we choose the first two operations, A will become empty first. For the third operation, A and B will become empty at the same time. For the fourth operation, B will become empty first. So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.
Notes:
0 <= N <= 10^9.
Answers within 10^-6 of the true value will be accepted as correct.
|
class Solution:
def soupServings(self, N: int) -> float:
if N>=10000:
return 1.0
L=N//25+1 if N%25>0 else N//25
res=dict()
res[0,0]=0.5
for l in range(1,L+1):
res[l,0]=0.0
res[0,l]=1.0
for m in range(1,L+1):
for n in range(1,L+1):
res[m,n]=0.25*(res[max([m-4,0]),n]+res[max([m-3,0]),max([n-1,0])]+res[max([m-2,0]),max(n-2,0)]+res[max(m-1,0),max(n-3,0)])
return res[L,L]
|
There are two types of soup: type A and type B. Initially we have N ml of each type of soup. There are four kinds of operations:
Serve 100 ml of soup A and 0 ml of soup B
Serve 75 ml of soup A and 25 ml of soup B
Serve 50 ml of soup A and 50 ml of soup B
Serve 25 ml of soup A and 75 ml of soup B
When we serve some soup, we give it to someone and we no longer have it. Each turn, we will choose from the four operations with equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as we can. We stop once we no longer have some quantity of both types of soup.
Note that we do not have the operation where all 100 ml's of soup B are used first.
Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time.
Example:
Input: N = 50
Output: 0.625
Explanation:
If we choose the first two operations, A will become empty first. For the third operation, A and B will become empty at the same time. For the fourth operation, B will become empty first. So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.
Notes:
0 <= N <= 10^9.
Answers within 10^-6 of the true value will be accepted as correct.
|
# class Solution:
# def soupServings(self, N: int) -> float:
# n=N//25 + (N % 25 > 0)
# dp=[[0]*(n+1) for i in range(n+1)]
# dp[-1][-1]=1
# x=[-4,-3,-2,-1]
# y=[0,-1,-2,-3]
# for i in range(n,0,-1):
# for j in range(n,0,-1):
# for dx,dy in zip(x,y):
# if i+dx>=0 and i+dy>=0:
# dp[i+dx][j+dy]+=dp[i][j]*(0.25)
# elif j+dy<0:
# dp[i+dx][0]+=dp[i][j]*(0.25)
# elif i+dx<0:
# dp[0][j+dy]+=dp[i][j]*(0.25)
# elif i+dx<0 and j+dy<0:
# dp[0][0]+=dp[i][j]*(0.25)
# Sum=0
# for j in range(n+1):
# Sum+=dp[0][j]
# return Sum - dp[0][0] / 2
class Solution:
def soupServings(self, N: int) -> float:
N = N//25 + (N % 25 > 0)
if N >= 500:
return 1
dp = [[0]*(N+1) for _ in range(N+1)]
operations = [(4, 0), (3, 1), (2, 2), (1, 3)]
dp[-1][-1] = 1
for i in range(N, 0, -1):
for j in range(N, 0, -1):
for a, b in operations:
if i-a < 0 and j-b < 0:
dp[0][0] += dp[i][j]*0.25
elif i-a < 0:
dp[0][j-b] += dp[i][j]*0.25
elif j-b < 0:
dp[i-a][0] += dp[i][j]*0.25
else:
dp[i-a][j-b] += dp[i][j]*0.25
a_total = 0
for i in range(N+1):
a_total += dp[0][i]
return a_total - dp[0][0] / 2
|
There are two types of soup: type A and type B. Initially we have N ml of each type of soup. There are four kinds of operations:
Serve 100 ml of soup A and 0 ml of soup B
Serve 75 ml of soup A and 25 ml of soup B
Serve 50 ml of soup A and 50 ml of soup B
Serve 25 ml of soup A and 75 ml of soup B
When we serve some soup, we give it to someone and we no longer have it. Each turn, we will choose from the four operations with equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as we can. We stop once we no longer have some quantity of both types of soup.
Note that we do not have the operation where all 100 ml's of soup B are used first.
Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time.
Example:
Input: N = 50
Output: 0.625
Explanation:
If we choose the first two operations, A will become empty first. For the third operation, A and B will become empty at the same time. For the fourth operation, B will become empty first. So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.
Notes:
0 <= N <= 10^9.
Answers within 10^-6 of the true value will be accepted as correct.
|
class Solution:
def soupServings(self, N: int) -> float:
n=N//25 + (N % 25 > 0)
if n>=500:
return 1
dp=[[0]*(n+1) for i in range(n+1)]
dp[-1][-1]=1
x=[-4,-3,-2,-1]
y=[0,-1,-2,-3]
for i in range(n,0,-1):
for j in range(n,0,-1):
for dx,dy in zip(x,y):
if i+dx<0 and j+dy<0:
dp[0][0]+=dp[i][j]*(0.25)
elif i+dx<0:
dp[0][j+dy]+=dp[i][j]*(0.25)
elif j+dy<0:
dp[i+dx][0]+=dp[i][j]*(0.25)
else:
dp[i+dx][j+dy]+=dp[i][j]*(0.25)
Sum=0
for j in range(n+1):
Sum+=dp[0][j]
return Sum - dp[0][0] / 2
# class Solution:
# def soupServings(self, N: int) -> float:
# N = N//25 + (N % 25 > 0)
# if N >= 500:
# return 1
# dp = [[0]*(N+1) for _ in range(N+1)]
# operations = [(4, 0), (3, 1), (2, 2), (1, 3)]
# dp[-1][-1] = 1
# for i in range(N, 0, -1):
# for j in range(N, 0, -1):
# for a, b in operations:
# if i-a < 0 and j-b < 0:
# dp[0][0] += dp[i][j]*0.25
# elif i-a < 0:
# dp[0][j-b] += dp[i][j]*0.25
# elif j-b < 0:
# dp[i-a][0] += dp[i][j]*0.25
# else:
# dp[i-a][j-b] += dp[i][j]*0.25
# a_total = 0
# for i in range(N+1):
# a_total += dp[0][i]
# return a_total - dp[0][0] / 2
|
There are two types of soup: type A and type B. Initially we have N ml of each type of soup. There are four kinds of operations:
Serve 100 ml of soup A and 0 ml of soup B
Serve 75 ml of soup A and 25 ml of soup B
Serve 50 ml of soup A and 50 ml of soup B
Serve 25 ml of soup A and 75 ml of soup B
When we serve some soup, we give it to someone and we no longer have it. Each turn, we will choose from the four operations with equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as we can. We stop once we no longer have some quantity of both types of soup.
Note that we do not have the operation where all 100 ml's of soup B are used first.
Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time.
Example:
Input: N = 50
Output: 0.625
Explanation:
If we choose the first two operations, A will become empty first. For the third operation, A and B will become empty at the same time. For the fourth operation, B will become empty first. So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.
Notes:
0 <= N <= 10^9.
Answers within 10^-6 of the true value will be accepted as correct.
|
# class Solution:
# def soupServings(self, N: int) -> float:
# n=N//25 + (N % 25 > 0)
# dp=[[0]*(n+1) for i in range(n+1)]
# M=[[0]*(n+1) for i in range(n+1)]
# dp[n][n]=1
# x=[-4,-3,-2,-1]
# y=[0,-1,-2,-3]
# for i in range(n,1,-1):
# for j in range(n,1,-1):
# if dp[i][j]>0:
# for dx,dy in zip(x,y):
# if i+dx>=0 and i+dy>=0:
# dp[i+dx][j+dy]+=dp[i][j]*(0.25)
# elif i+dx>=0 and j+dy<0:
# dp[i+dx][0]+=dp[i][j]*(0.25)
# elif i+dx<0 and j+dy>=0:
# dp[0][j+dy]+=dp[i][j]*(0.25)
# elif i+dx<0 and j+dy<0:
# dp[0][0]+=dp[i][j]*(0.25)
# Sum=0
# for j in range(len(dp[0])):
# Sum+=dp[0][j]
# return Sum-dp[0][0]/2
class Solution:
def soupServings(self, N: int) -> float:
N = N//25 + (N % 25 > 0)
if N >= 500:
return 1
dp = [[0]*(N+1) for _ in range(N+1)]
operations = [(4, 0), (3, 1), (2, 2), (1, 3)]
dp[-1][-1] = 1
for i in range(N, 0, -1):
for j in range(N, 0, -1):
for a, b in operations:
if i-a < 0 and j-b < 0:
dp[0][0] += dp[i][j]*0.25
elif i-a < 0:
dp[0][j-b] += dp[i][j]*0.25
elif j-b < 0:
dp[i-a][0] += dp[i][j]*0.25
else:
dp[i-a][j-b] += dp[i][j]*0.25
a_total = 0
for i in range(N+1):
a_total += dp[0][i]
return a_total - dp[0][0] / 2
|
There are two types of soup: type A and type B. Initially we have N ml of each type of soup. There are four kinds of operations:
Serve 100 ml of soup A and 0 ml of soup B
Serve 75 ml of soup A and 25 ml of soup B
Serve 50 ml of soup A and 50 ml of soup B
Serve 25 ml of soup A and 75 ml of soup B
When we serve some soup, we give it to someone and we no longer have it. Each turn, we will choose from the four operations with equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as we can. We stop once we no longer have some quantity of both types of soup.
Note that we do not have the operation where all 100 ml's of soup B are used first.
Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time.
Example:
Input: N = 50
Output: 0.625
Explanation:
If we choose the first two operations, A will become empty first. For the third operation, A and B will become empty at the same time. For the fourth operation, B will become empty first. So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.
Notes:
0 <= N <= 10^9.
Answers within 10^-6 of the true value will be accepted as correct.
|
class Solution:
def soupServings(self, N: int) -> float:
import numpy as np
if N > 5000: return 1
if N == 0:
return 0.5
if N % 25 == 0:
N = N // 25
else:
N = N // 25 + 1
# N is the dimension
# Initial Square equals to ( N + 1 ) * ( N + 1 )
Matrix = [ [ 0.0 for i in range( N + 1 ) ] for j in range( N + 1 ) ]
Matrix = np.matrix( Matrix )
Matrix[ N, N ] = 1
Explore_List = [ (N,N) ];
while( Explore_List ):
New_List = set()
for x, y in Explore_List:
if( x != 0 and y != 0 ):
Matrix[ max( 0, x - 2 ), max( 0, y - 2 ) ] += Matrix[ x, y ] * 1/4
New_List.add( (max( 0, x - 2 ), max( 0, y - 2 )) )
Matrix[ max( 0, x - 1 ), max( 0, y - 3 ) ] += Matrix[ x, y ] * 1/4
New_List.add( (max( 0, x - 1 ), max( 0, y - 3 )) )
Matrix[ max( 0, x - 3 ), max( 0, y - 1 ) ] += Matrix[ x, y ] * 1/4
New_List.add( (max( 0, x - 3 ), max( 0, y - 1 )) )
Matrix[ max( 0, x - 4 ), max( 0, y - 0 ) ] += Matrix[ x, y ] * 1/4
New_List.add( (max( 0, x - 4 ), max( 0, y - 0 )) )
Explore_List = New_List
return Matrix[ 0 ].sum() - 1/2 * Matrix[ 0, 0 ]
|
There are two types of soup: type A and type B. Initially we have N ml of each type of soup. There are four kinds of operations:
Serve 100 ml of soup A and 0 ml of soup B
Serve 75 ml of soup A and 25 ml of soup B
Serve 50 ml of soup A and 50 ml of soup B
Serve 25 ml of soup A and 75 ml of soup B
When we serve some soup, we give it to someone and we no longer have it. Each turn, we will choose from the four operations with equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as we can. We stop once we no longer have some quantity of both types of soup.
Note that we do not have the operation where all 100 ml's of soup B are used first.
Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time.
Example:
Input: N = 50
Output: 0.625
Explanation:
If we choose the first two operations, A will become empty first. For the third operation, A and B will become empty at the same time. For the fourth operation, B will become empty first. So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.
Notes:
0 <= N <= 10^9.
Answers within 10^-6 of the true value will be accepted as correct.
|
class Solution:
def soupServings(self, N: int) -> float:
operations = [(100, 0), (75, 25), (50, 50), (25, 75)]
@lru_cache(maxsize=None)
def helper(remainA, remainB):
if remainA == 0 and remainB == 0:
return 0.5
if remainA == 0 or remainB == 0:
return remainA == 0
result = 0
for op in operations:
result += helper(max(0, remainA - op[0]), max(0, remainB - op[1]))
return result / 4
N = min(N, 4801)
return helper(N, N)
|
There are two types of soup: type A and type B. Initially we have N ml of each type of soup. There are four kinds of operations:
Serve 100 ml of soup A and 0 ml of soup B
Serve 75 ml of soup A and 25 ml of soup B
Serve 50 ml of soup A and 50 ml of soup B
Serve 25 ml of soup A and 75 ml of soup B
When we serve some soup, we give it to someone and we no longer have it. Each turn, we will choose from the four operations with equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as we can. We stop once we no longer have some quantity of both types of soup.
Note that we do not have the operation where all 100 ml's of soup B are used first.
Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time.
Example:
Input: N = 50
Output: 0.625
Explanation:
If we choose the first two operations, A will become empty first. For the third operation, A and B will become empty at the same time. For the fourth operation, B will become empty first. So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.
Notes:
0 <= N <= 10^9.
Answers within 10^-6 of the true value will be accepted as correct.
|
class Solution:
def soupServings(self, N: int) -> float:
def prob(A,B,dp):
if A==0 and B==0:
return 0.5
if A==0:
return 1.0
if dp[A][B]!=-1.0:
return dp[A][B]
else:
total_prob=0
total_prob+=1/4*prob(max(0,A-100),B,dp)
if B-25>0 or (A-75<=0 and B-25<=0):
total_prob+= 1/4*prob(max(0,A-75),max(0,B-25),dp)
if B-50>0 or (A-50<=0 and B-50<=0):
total_prob += 1/4*prob(max(0,A-50),max(0,B-50),dp)
if B-75>0 or (A-25<=0 and B-75<=0):
total_prob += 1/4*prob(max(0,A-25),max(0,B-75),dp)
dp[A][B]=total_prob
return dp[A][B]
if N>4800:
return 1.0
dp=[[-1.0 for i in range(N+1)] for j in range(N+1)]
return prob(N,N,dp)
|
There are two types of soup: type A and type B. Initially we have N ml of each type of soup. There are four kinds of operations:
Serve 100 ml of soup A and 0 ml of soup B
Serve 75 ml of soup A and 25 ml of soup B
Serve 50 ml of soup A and 50 ml of soup B
Serve 25 ml of soup A and 75 ml of soup B
When we serve some soup, we give it to someone and we no longer have it. Each turn, we will choose from the four operations with equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as we can. We stop once we no longer have some quantity of both types of soup.
Note that we do not have the operation where all 100 ml's of soup B are used first.
Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time.
Example:
Input: N = 50
Output: 0.625
Explanation:
If we choose the first two operations, A will become empty first. For the third operation, A and B will become empty at the same time. For the fourth operation, B will become empty first. So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.
Notes:
0 <= N <= 10^9.
Answers within 10^-6 of the true value will be accepted as correct.
|
class Solution:
def soupServings(self, N: int) -> float:
if(N>5000):
return 1
dp = [[-1 for i in range(N+1)] for j in range(N+1)]
return (self.helper(N,N,dp))
def helper(self,A,B,dp):
if(A<=0 and B<=0):
return 0.5
if(A<=0):
return 1
if(B<=0):
return 0
if(dp[A][B]!=-1):
return dp[A][B]
dp[A][B] = (self.helper(A-100,B-0,dp) + self.helper(A-75,B-25,dp) + self.helper(A-50,B-50,dp)+self.helper(A-25,B-75,dp))*0.25
return dp[A][B]
|
There are two types of soup: type A and type B. Initially we have N ml of each type of soup. There are four kinds of operations:
Serve 100 ml of soup A and 0 ml of soup B
Serve 75 ml of soup A and 25 ml of soup B
Serve 50 ml of soup A and 50 ml of soup B
Serve 25 ml of soup A and 75 ml of soup B
When we serve some soup, we give it to someone and we no longer have it. Each turn, we will choose from the four operations with equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as we can. We stop once we no longer have some quantity of both types of soup.
Note that we do not have the operation where all 100 ml's of soup B are used first.
Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time.
Example:
Input: N = 50
Output: 0.625
Explanation:
If we choose the first two operations, A will become empty first. For the third operation, A and B will become empty at the same time. For the fourth operation, B will become empty first. So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.
Notes:
0 <= N <= 10^9.
Answers within 10^-6 of the true value will be accepted as correct.
|
class Solution:
def soupServings(self, N: int) -> float:
compressed_N = N // 25
N = compressed_N + (1 if (N-compressed_N*25)>0 else 0)
mem = {}
def dp(a, b):
if (a, b) in mem:
return mem[(a,b)]
else:
if a <= 0 or b <= 0:
result = 0.5 if a <=0 and b <= 0 else 1.0 if a <= 0 else 0.0
else:
result = 0.25 * (dp(a-4, b) + dp(a-3, b-1) + dp(a-2, b-2) + dp(a-1, b-3))
mem[(a,b)] = result
return result
if N <= 200:
return dp(N, N)
else:
for i in range(200, N+1):
current_result = dp(i, i)
if 1 - current_result < 1e-6:
return 1.0
return current_result
|
There are two types of soup: type A and type B. Initially we have N ml of each type of soup. There are four kinds of operations:
Serve 100 ml of soup A and 0 ml of soup B
Serve 75 ml of soup A and 25 ml of soup B
Serve 50 ml of soup A and 50 ml of soup B
Serve 25 ml of soup A and 75 ml of soup B
When we serve some soup, we give it to someone and we no longer have it. Each turn, we will choose from the four operations with equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as we can. We stop once we no longer have some quantity of both types of soup.
Note that we do not have the operation where all 100 ml's of soup B are used first.
Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time.
Example:
Input: N = 50
Output: 0.625
Explanation:
If we choose the first two operations, A will become empty first. For the third operation, A and B will become empty at the same time. For the fourth operation, B will become empty first. So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.
Notes:
0 <= N <= 10^9.
Answers within 10^-6 of the true value will be accepted as correct.
|
class Solution:
def soupServings(self, N: int) -> float:
memo = {}
if N > 4800:
return 1
def dp(a ,b):
if (a, b) in memo: return memo[a, b]
if a <= 0 and b > 0: return 1
if a <= 0 and b <= 0: return 0.5
if a > 0 and b <= 0: return 0
memo[a, b] = (dp(a - 100, b) + dp(a - 75, b - 25) + dp(a - 50, b - 50) + dp(a - 25, b - 75)) / 4
return memo[a, b]
return dp(N, N)
|
There are two types of soup: type A and type B. Initially we have N ml of each type of soup. There are four kinds of operations:
Serve 100 ml of soup A and 0 ml of soup B
Serve 75 ml of soup A and 25 ml of soup B
Serve 50 ml of soup A and 50 ml of soup B
Serve 25 ml of soup A and 75 ml of soup B
When we serve some soup, we give it to someone and we no longer have it. Each turn, we will choose from the four operations with equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as we can. We stop once we no longer have some quantity of both types of soup.
Note that we do not have the operation where all 100 ml's of soup B are used first.
Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time.
Example:
Input: N = 50
Output: 0.625
Explanation:
If we choose the first two operations, A will become empty first. For the third operation, A and B will become empty at the same time. For the fourth operation, B will become empty first. So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.
Notes:
0 <= N <= 10^9.
Answers within 10^-6 of the true value will be accepted as correct.
|
class Solution:
def soupServings(self, N: int) -> float:
compressed_N = N // 25
N = compressed_N + (1 if (N-compressed_N*25)>0 else 0)
mem = {}
def dp(a, b):
if (a, b) in mem:
return mem[(a,b)]
else:
if a <= 0 or b <= 0:
result = 0.5 if a <=0 and b <= 0 else 1.0 if a <= 0 else 0.0
else:
result = 0.25 * (dp(a-4, b) + dp(a-3, b-1) + dp(a-2, b-2) + dp(a-1, b-3))
mem[(a,b)] = result
return result
if N <= 100:
return dp(N, N)
else:
for i in range(100, N+1):
current_result = dp(i, i)
if 1 - current_result < 1e-6:
return 1.0
return current_result
|
There are two types of soup: type A and type B. Initially we have N ml of each type of soup. There are four kinds of operations:
Serve 100 ml of soup A and 0 ml of soup B
Serve 75 ml of soup A and 25 ml of soup B
Serve 50 ml of soup A and 50 ml of soup B
Serve 25 ml of soup A and 75 ml of soup B
When we serve some soup, we give it to someone and we no longer have it. Each turn, we will choose from the four operations with equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as we can. We stop once we no longer have some quantity of both types of soup.
Note that we do not have the operation where all 100 ml's of soup B are used first.
Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time.
Example:
Input: N = 50
Output: 0.625
Explanation:
If we choose the first two operations, A will become empty first. For the third operation, A and B will become empty at the same time. For the fourth operation, B will become empty first. So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.
Notes:
0 <= N <= 10^9.
Answers within 10^-6 of the true value will be accepted as correct.
|
class Solution:
def soupServings(self, N: int) -> float:
# 5:02 10/4/20
def dfs(a,b):
if a<=0 and b<=0:
return 0.5
if a<=0 and b>0:
return 1
if a>0 and b<=0:
return 0
if memo[a][b]!=-1:
return memo[a][b]
memo[a][b]=0.25*(dfs(a-4,b)+dfs(a-3,b-1)+dfs(a-2,b-2)+dfs(a-1,b-3))
return memo[a][b]
if N>=5000:
return 1
n=N//25+int(N%25>0)
memo=[[-1]*200 for _ in range(200)]
return dfs(n,n)
|
There are two types of soup: type A and type B. Initially we have N ml of each type of soup. There are four kinds of operations:
Serve 100 ml of soup A and 0 ml of soup B
Serve 75 ml of soup A and 25 ml of soup B
Serve 50 ml of soup A and 50 ml of soup B
Serve 25 ml of soup A and 75 ml of soup B
When we serve some soup, we give it to someone and we no longer have it. Each turn, we will choose from the four operations with equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as we can. We stop once we no longer have some quantity of both types of soup.
Note that we do not have the operation where all 100 ml's of soup B are used first.
Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time.
Example:
Input: N = 50
Output: 0.625
Explanation:
If we choose the first two operations, A will become empty first. For the third operation, A and B will become empty at the same time. For the fourth operation, B will become empty first. So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.
Notes:
0 <= N <= 10^9.
Answers within 10^-6 of the true value will be accepted as correct.
|
class Solution:
def soupServings(self, N: int) -> float:
Q, R = divmod(N, 25)
N = Q + (R > 0)
if N >= 500: return 1
memo = {}
def dp(x, y):
if (x, y) not in memo:
if x <= 0 or y <= 0:
ans = 0.5 if x<=0 and y<=0 else 1.0 if x<=0 else 0.0
else:
ans = 0.25 * (dp(x-4,y)+dp(x-3,y-1)+dp(x-2,y-2)+dp(x-1,y-3))
memo[x, y] = ans
return memo[x, y]
return dp(N, N)
|
There are two types of soup: type A and type B. Initially we have N ml of each type of soup. There are four kinds of operations:
Serve 100 ml of soup A and 0 ml of soup B
Serve 75 ml of soup A and 25 ml of soup B
Serve 50 ml of soup A and 50 ml of soup B
Serve 25 ml of soup A and 75 ml of soup B
When we serve some soup, we give it to someone and we no longer have it. Each turn, we will choose from the four operations with equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as we can. We stop once we no longer have some quantity of both types of soup.
Note that we do not have the operation where all 100 ml's of soup B are used first.
Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time.
Example:
Input: N = 50
Output: 0.625
Explanation:
If we choose the first two operations, A will become empty first. For the third operation, A and B will become empty at the same time. For the fourth operation, B will become empty first. So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.
Notes:
0 <= N <= 10^9.
Answers within 10^-6 of the true value will be accepted as correct.
|
class Solution:
def soupServings(self, N: int) -> float:
if N >= 12500:
return 1
self.memory = {}
return self.helper(N, N)
def helper(self, A, B):
if (A, B) in self.memory:
return self.memory[(A,B)]
elif A <= 0 and B <= 0:
return 0.5
elif B <= 0:
return 0
elif A <= 0:
return 1
prob = 0
# option1
prob += 0.25*self.helper(A-100, B)
# option2
prob += 0.25*self.helper(A-75, B-25)
# option3
prob += 0.25*self.helper(A-50, B-50)
# option4
prob += 0.25*self.helper(A-25, B-75)
self.memory[(A,B)] = prob
return prob
|
There are two types of soup: type A and type B. Initially we have N ml of each type of soup. There are four kinds of operations:
Serve 100 ml of soup A and 0 ml of soup B
Serve 75 ml of soup A and 25 ml of soup B
Serve 50 ml of soup A and 50 ml of soup B
Serve 25 ml of soup A and 75 ml of soup B
When we serve some soup, we give it to someone and we no longer have it. Each turn, we will choose from the four operations with equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as we can. We stop once we no longer have some quantity of both types of soup.
Note that we do not have the operation where all 100 ml's of soup B are used first.
Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time.
Example:
Input: N = 50
Output: 0.625
Explanation:
If we choose the first two operations, A will become empty first. For the third operation, A and B will become empty at the same time. For the fourth operation, B will become empty first. So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.
Notes:
0 <= N <= 10^9.
Answers within 10^-6 of the true value will be accepted as correct.
|
class Solution:
def soupServings(self, N: int) -> float:
if N > 4800: return 1
@lru_cache(None)
def dfs(a, b):
if a <= 0 and b <= 0:
return 0.5
if a <= 0: return 1
if b <= 0: return 0
return (dfs(a-100, b)+dfs(a-75,b-25)+dfs(a-50,b-50)+dfs(a-25,b-75))/4
return dfs(N, N)
|
There are two types of soup: type A and type B. Initially we have N ml of each type of soup. There are four kinds of operations:
Serve 100 ml of soup A and 0 ml of soup B
Serve 75 ml of soup A and 25 ml of soup B
Serve 50 ml of soup A and 50 ml of soup B
Serve 25 ml of soup A and 75 ml of soup B
When we serve some soup, we give it to someone and we no longer have it. Each turn, we will choose from the four operations with equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as we can. We stop once we no longer have some quantity of both types of soup.
Note that we do not have the operation where all 100 ml's of soup B are used first.
Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time.
Example:
Input: N = 50
Output: 0.625
Explanation:
If we choose the first two operations, A will become empty first. For the third operation, A and B will become empty at the same time. For the fourth operation, B will become empty first. So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.
Notes:
0 <= N <= 10^9.
Answers within 10^-6 of the true value will be accepted as correct.
|
class Solution:
def soupServings(self, N: int) -> float:
if N > 5555:
return 1
memo = dict()
def Pa(A, B):
if (A, B) in memo:
return memo[(A, B)]
if A <= 0 and B <= 0:
return 0.5
if A <= 0:
return 1
if B <= 0:
return 0
else:
memo[(A, B)] = (Pa(A-100, B) + Pa(A-75, B-25) + Pa(A-50, B-50) + Pa(A-25, B-75)) / 4
return memo[(A, B)]
return Pa(N, N)
|
Given a string representing a code snippet, you need to implement a tag validator to parse the code and return whether it is valid. A code snippet is valid if all the following rules hold:
The code must be wrapped in a valid closed tag. Otherwise, the code is invalid.
A closed tag (not necessarily valid) has exactly the following format : <TAG_NAME>TAG_CONTENT</TAG_NAME>. Among them, <TAG_NAME> is the start tag, and </TAG_NAME> is the end tag. The TAG_NAME in start and end tags should be the same. A closed tag is valid if and only if the TAG_NAME and TAG_CONTENT are valid.
A valid TAG_NAME only contain upper-case letters, and has length in range [1,9]. Otherwise, the TAG_NAME is invalid.
A valid TAG_CONTENT may contain other valid closed tags, cdata and any characters (see note1) EXCEPT unmatched <, unmatched start and end tag, and unmatched or closed tags with invalid TAG_NAME. Otherwise, the TAG_CONTENT is invalid.
A start tag is unmatched if no end tag exists with the same TAG_NAME, and vice versa. However, you also need to consider the issue of unbalanced when tags are nested.
A < is unmatched if you cannot find a subsequent >. And when you find a < or </, all the subsequent characters until the next > should be parsed as TAG_NAME (not necessarily valid).
The cdata has the following format : <![CDATA[CDATA_CONTENT]]>. The range of CDATA_CONTENT is defined as the characters between <![CDATA[ and the first subsequent ]]>.
CDATA_CONTENT may contain any characters. The function of cdata is to forbid the validator to parse CDATA_CONTENT, so even it has some characters that can be parsed as tag (no matter valid or invalid), you should treat it as regular characters.
Valid Code Examples:
Input: "<DIV>This is the first line <![CDATA[<div>]]></DIV>"
Output: True
Explanation:
The code is wrapped in a closed tag : <DIV> and </DIV>.
The TAG_NAME is valid, the TAG_CONTENT consists of some characters and cdata.
Although CDATA_CONTENT has unmatched start tag with invalid TAG_NAME, it should be considered as plain text, not parsed as tag.
So TAG_CONTENT is valid, and then the code is valid. Thus return true.
Input: "<DIV>>> ![cdata[]] <![CDATA[<div>]>]]>]]>>]</DIV>"
Output: True
Explanation:
We first separate the code into : start_tag|tag_content|end_tag.
start_tag -> "<DIV>"
end_tag -> "</DIV>"
tag_content could also be separated into : text1|cdata|text2.
text1 -> ">> ![cdata[]] "
cdata -> "<![CDATA[<div>]>]]>", where the CDATA_CONTENT is "<div>]>"
text2 -> "]]>>]"
The reason why start_tag is NOT "<DIV>>>" is because of the rule 6.
The reason why cdata is NOT "<![CDATA[<div>]>]]>]]>" is because of the rule 7.
Invalid Code Examples:
Input: "<A> <B> </A> </B>"
Output: False
Explanation: Unbalanced. If "<A>" is closed, then "<B>" must be unmatched, and vice versa.
Input: "<DIV> div tag is not closed <DIV>"
Output: False
Input: "<DIV> unmatched < </DIV>"
Output: False
Input: "<DIV> closed tags with invalid tag name <b>123</b> </DIV>"
Output: False
Input: "<DIV> unmatched tags with invalid tag name </1234567890> and <CDATA[[]]> </DIV>"
Output: False
Input: "<DIV> unmatched start tag <B> and unmatched end tag </C> </DIV>"
Output: False
Note:
For simplicity, you could assume the input code (including the any characters mentioned above) only contain letters, digits, '<','>','/','!','[',']' and ' '.
|
class Solution:
def isValid(self, code):
"""
:type code: str
:rtype: bool
"""
def parseTag(src, i):
j = i
tag, i = findtag(src, i)
if not tag:
return False, j
res, i = parseContent(src, i)
e = i + len(tag) + 3
return (True, e) if src[i: e] == '</' + tag + '>' else (False, j)
def parseContent(src, i):
j, res = i, False
while i < len(src):
res, i = parseText(src, i)
if res:
continue
res, i = parseCDData(src, i)
if res:
continue
res, i = parseTag(src, i)
if res:
continue
break
return True, i
def parseCDData(src, i):
s = src.find('<![CDATA[', i)
if s != i:
return False, i
e = src.find(']]>', i)
return (True, e+3) if e != -1 else (False, i)
def parseText(src, i):
j = i
while i < len(src) and src[i] != '<':
i += 1
return j != i, i
def findtag(src, i):
if src[i] != '<':
return "", i
e = src.find('>', i+1)
if e == -1 or e - i - 1 > 9 or e - i - 1 < 1:
return "", e
s = 1
while s < e - i and src[i+s].isupper():
s += 1
return (src[i+1: e], e+1) if s >= e - i else ("", e)
# start to check
return parseTag(code, 0) == (True, len(code))
|
Given a string representing a code snippet, you need to implement a tag validator to parse the code and return whether it is valid. A code snippet is valid if all the following rules hold:
The code must be wrapped in a valid closed tag. Otherwise, the code is invalid.
A closed tag (not necessarily valid) has exactly the following format : <TAG_NAME>TAG_CONTENT</TAG_NAME>. Among them, <TAG_NAME> is the start tag, and </TAG_NAME> is the end tag. The TAG_NAME in start and end tags should be the same. A closed tag is valid if and only if the TAG_NAME and TAG_CONTENT are valid.
A valid TAG_NAME only contain upper-case letters, and has length in range [1,9]. Otherwise, the TAG_NAME is invalid.
A valid TAG_CONTENT may contain other valid closed tags, cdata and any characters (see note1) EXCEPT unmatched <, unmatched start and end tag, and unmatched or closed tags with invalid TAG_NAME. Otherwise, the TAG_CONTENT is invalid.
A start tag is unmatched if no end tag exists with the same TAG_NAME, and vice versa. However, you also need to consider the issue of unbalanced when tags are nested.
A < is unmatched if you cannot find a subsequent >. And when you find a < or </, all the subsequent characters until the next > should be parsed as TAG_NAME (not necessarily valid).
The cdata has the following format : <![CDATA[CDATA_CONTENT]]>. The range of CDATA_CONTENT is defined as the characters between <![CDATA[ and the first subsequent ]]>.
CDATA_CONTENT may contain any characters. The function of cdata is to forbid the validator to parse CDATA_CONTENT, so even it has some characters that can be parsed as tag (no matter valid or invalid), you should treat it as regular characters.
Valid Code Examples:
Input: "<DIV>This is the first line <![CDATA[<div>]]></DIV>"
Output: True
Explanation:
The code is wrapped in a closed tag : <DIV> and </DIV>.
The TAG_NAME is valid, the TAG_CONTENT consists of some characters and cdata.
Although CDATA_CONTENT has unmatched start tag with invalid TAG_NAME, it should be considered as plain text, not parsed as tag.
So TAG_CONTENT is valid, and then the code is valid. Thus return true.
Input: "<DIV>>> ![cdata[]] <![CDATA[<div>]>]]>]]>>]</DIV>"
Output: True
Explanation:
We first separate the code into : start_tag|tag_content|end_tag.
start_tag -> "<DIV>"
end_tag -> "</DIV>"
tag_content could also be separated into : text1|cdata|text2.
text1 -> ">> ![cdata[]] "
cdata -> "<![CDATA[<div>]>]]>", where the CDATA_CONTENT is "<div>]>"
text2 -> "]]>>]"
The reason why start_tag is NOT "<DIV>>>" is because of the rule 6.
The reason why cdata is NOT "<![CDATA[<div>]>]]>]]>" is because of the rule 7.
Invalid Code Examples:
Input: "<A> <B> </A> </B>"
Output: False
Explanation: Unbalanced. If "<A>" is closed, then "<B>" must be unmatched, and vice versa.
Input: "<DIV> div tag is not closed <DIV>"
Output: False
Input: "<DIV> unmatched < </DIV>"
Output: False
Input: "<DIV> closed tags with invalid tag name <b>123</b> </DIV>"
Output: False
Input: "<DIV> unmatched tags with invalid tag name </1234567890> and <CDATA[[]]> </DIV>"
Output: False
Input: "<DIV> unmatched start tag <B> and unmatched end tag </C> </DIV>"
Output: False
Note:
For simplicity, you could assume the input code (including the any characters mentioned above) only contain letters, digits, '<','>','/','!','[',']' and ' '.
|
class Solution:
def isValid(self, code):
"""
:type code: str
:rtype: bool
"""
S=code
CDATA_BEGIN='![CDATA['
CDATA_END=']]>'
def collect_tag(i):
for j in range(i,len(S)):
if S[j]=='>':
break
else:
return None
return S[i+1:j]
def valid_tag(tag):
if 1<=len(tag)<=9 and all('A' <=c<= 'Z' for c in tag):
return True
else:
return False
if not S or S[0]!='<':
return False
#print('###########1111############')
tag=collect_tag(0)
#print(tag)
if not tag or not S.startswith('<{}>'.format(tag)) or not S.endswith('</{}>'.format(tag)) or not valid_tag(tag):
return False
S=S[len(tag)+2:-len(tag)-3]
i=0
stack=[]
while i<len(S):
if S[i]=='<':
tag=collect_tag(i)
#print(tag)
if not tag:
return False
if tag.startswith(CDATA_BEGIN):
while i<len(S) and S[i:i+3]!=CDATA_END:
i+=1
if S[i:i+3]!=CDATA_END:
return False
i+=2
elif tag.startswith('/'):
tag=tag[1:]
if not valid_tag(tag) or not stack or stack.pop()!=tag:
return False
else:
if not valid_tag(tag):
return False
stack.append(tag)
i+=1
return not stack
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
from collections import Counter
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
c = dict(Counter(A).most_common())
# print(c)
m1 = max(c.values())
# A = list(set(A))
# A.sort()
index = {}
# for i in range(len(A)):
# index[A[i]]=i
dp = [[2] * len(A) for i in A]
m = 2
for i in range(len(A)):
# print(\"I=\", i)
# index[A[i+1]]=(i+1)
for j in range(i+1, len(A)):
# index[A[j]]=(j)
a = A[i]
c = A[j]
b = 2 * a - c
# print(b,a,c)
if b in index :
# print(\"B {} in index \".format(b))
# print(b,a,c,i,j)
dp[i][j] = dp[index[b]][i] + 1
index[A[i]]=i
m = max(m, max(dp[i]))
# # print(A)
# for i,d in enumerate(dp):
# print(A[i],d)
return max(m,m1)
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
length = len(A)
onleft = set()
onleftl = []
onright = [0 for _ in range(501)]
toextend = [{} for _ in range(501)]
res = 2
for v in A:
onright[v] += 1
for i in range(0, length):
val = A[i]
tex = toextend[val]
onright[val] -= 1
for lval in onleftl:
diff = val - lval
nextval = val + diff
if nextval > 500 or nextval < 0 or onright[nextval] == 0:
continue
if diff in tex:
c = tex[diff] + 1
else:
c = 3
if c > res:
res = c
toextend[nextval][diff] = c
if val not in onleft:
onleftl.append(val)
onleft.add(val)
return res
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
n = len(A)
dp = [[2 for c in range(n)] for r in range(n)]
visited = {}
res = 2
for i in range(n - 1):
for j in range(i + 1, n):
prev = A[i] * 2 - A[j]
if prev < 0 or prev not in visited:
continue
dp[i][j] = dp[visited[prev]][i] + 1
res = max(res, dp[i][j])
visited[A[i]] = i
return res
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
res, n = 1, len(A)
dp = [{} for _ in range(n)]
for i in range(1, n):
for j in range(i-1, -1, -1):
d = A[i] - A[j]
if d in dp[i]: continue
if d in dp[j]:
dp[i][d] = dp[j][d]+1
else:
dp[i][d] = 2
res = max(res, dp[i][d])
# print(dp)
return res
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
dp = {}
maxValue = 1;
for i in range(len(A)):
for j in range(0, i):
dp[i, A[i] - A[j]] = dp.get((j, A[i] - A[j]), 0) + 1
maxValue = max(maxValue, dp[i, A[i] - A[j]])
return maxValue + 1
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
dp=[dict() for a in A]
for idx, a in enumerate(A):
for j in range(idx):
diff=a-A[j]
dp[idx][diff]=dp[j].get(diff,1)+1
def get_len(d):
if not d:
return 0
return max(d.values())
return max(map(get_len,dp))
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
a = len(A)
dp = [[0]*a for _ in range(a)] # dp array
index = [-1]*20001#index array
maximum = 2
for i in range(0,a):
dp[i] = [2]*a
for j in range(i+1, a):
first = A[i]*2-A[j]
if first < 0 or index[first]==-1:
continue
dp[i][j] = dp[index[first]][i]+1
maximum = max(maximum,dp[i][j] )
index[A[i]] = i
return maximum
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
if not A:
return 0
if len(A) == 1 or len(A) == 2:
return len(A)
D = [dict() for _ in range(len(A))]
ans = 0
for i, a in enumerate(A[1:], 1):
for j in range(i):
if a - A[j] not in D[j]:
D[i][a - A[j]] = 2
else:
D[i][a - A[j]] = D[j][a - A[j]] + 1
ans = max(ans, max(D[i].values()))
return ans
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
if len(A) < 3:
return len(A)
dp = [ {} for i in range(len(A))]
m = 2
for i in range(1, len(A)):
for j in range(i): # here we have to iterate from 0 to i-1 and not i-1 to 0.
diff = A[i] - A[j]
if diff in dp[j]:
dp[i][diff] = dp[j][diff]+1
if m < dp[i][diff]:
m = dp[i][diff]
else:
dp[i][diff] = 2
return m
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
a = len(A)
dp = [[0]*a for _ in range(a)]
index = [-1]*20001
maximum = 2
for i in range(0,a):
dp[i] = [2]*a
for j in range(i+1, a):
first = A[i]*2-A[j]
if first < 0 or index[first]==-1:
continue
else:
dp[i][j] = dp[index[first]][i]+1
maximum = max(maximum,dp[i][j] )
index[A[i]] = i
return maximum
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
n = len(A)
dp = [{} for _ in range(n)]
ans = 0
for i in range(n):
dp[i][0] = 1
for j in range(i):
diff = A[i] - A[j]
if diff not in dp[j]:
dp[i][diff] = 2
else:
dp[i][diff] = dp[j][diff] + 1
ans = max(ans, max([dp[i][key] for key in dp[i]]))
return ans
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
from collections import defaultdict
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
highest = 0
offsets = [None] * len(A)
for i in range(len(A)):
offsets[i] = defaultdict(int)
for i in range(len(A) - 1,-1,-1):
# go forwards
for j in range(i,-1,-1):
offset = A[i] - A[j]
if offset == 0:
continue
offsets[i][offset] = 1
# go backwards
seen_offsets = set()
for j in range(i,len(A)):
offset = (A[i] - A[j]) * -1
if offset == 0 or offset in seen_offsets:
continue
seen_offsets.add(offset)
# increment only for the first time we've seen this offset going back
offsets[i][offset] += offsets[j][offset]
if offsets[i][offset] > highest:
highest = offsets[i][offset]
#for offset in offsets:
# print(offset)
return highest + 1
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
dp = []
for i, x in enumerate(A):
nd = collections.defaultdict(int)
dp.append(nd)
for j in range(i):
curr_diff = x - A[j]
dp[i][curr_diff] = dp[j][curr_diff] + 1
return max(max(y.values()) for y in dp) + 1
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
ALen = len(A)
dictList = [defaultdict(lambda: 1) for _ in range(ALen)]
ans = 2
for i, num in enumerate(A):
for j in range(i-1, -1, -1):
delta = A[i] - A[j]
if delta not in dictList[i]:
dictList[i][delta] = 1 + dictList[j][delta]
ans = max(ans, dictList[i][delta])
return ans
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
from collections import defaultdict
d = [{} for _ in range(len(A))]
res = 2
for i, x in enumerate(A):
for j in range(i):
diff = x - A[j]
if diff in d[j]:
d[i][diff] = d[j][diff] + 1
# d[j].pop(diff)
res = max(res, d[i][diff])
else:
d[i][diff] = 2
return res
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
dp = []
for i, x in enumerate(A):
nd = collections.defaultdict(int)
dp.append(nd)
for j in range(i):
curr_diff = x - A[j]
dp[i][curr_diff] = dp[j][curr_diff] + 1
return max(max(y.values()) for y in dp) + 1
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
n = len(A)
if n <= 1:
return n
ap = [None] * n
for i in range(n):
ap[i] = dict()
for j in range(1, n):
for i in range(0, j):
diff = A[j] - A[i]
ap[j][diff] = ap[i].get(diff, 1) + 1
ans = 0
for item in ap[1:]:
vals = max(item.values())
ans = max(ans, vals)
return ans
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, nums: List[int]) -> int:
n = len(nums)
if n == 2:
return n
dp = [{} for i in range(n)]
res = 0
for i in range(1, n):
for j in range(i):
dis = nums[i] - nums[j]
# 在前面的dp[j]中 用get()寻找dp中已有的数据。
# 如果没有,说明是基本状态,用1初始化,+1为2
x = dp[j].get(dis, 1)+1
dp[i][dis] = x
res = max(res, max(dp[i].values()))
return res
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
from collections import defaultdict
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
N = len(A)
dp = [defaultdict(lambda: 1) for _ in range(N)]
for i in range(N):
for j in range(i+1, N):
diff = A[j] - A[i]
dp[j][diff] = dp[i][diff] + 1
return max([max(d.values()) for d in dp])
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
length = len(A)
onleft = set()
onleftl = []
onright = [0 for _ in range(501)]
toextend = [{} for _ in range(501)]
res = 2
for v in A:
onright[v] += 1
for i in range(0, length):
val = A[i]
tex = toextend[val]
onright[val] -= 1
for lval in onleft:
diff = val - lval
nextval = val + diff
if nextval > 500 or nextval < 0 or onright[nextval] == 0:
continue
if diff in tex:
c = tex[diff] + 1
else:
c = 3
if c > res:
res = c
toextend[nextval][diff] = c
if val not in onleft:
onleftl.append(val)
onleft.add(val)
return res
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
memo = [{} for _ in range(len(A))]
for i in range(len(A)):
for j in range(i):
diff = A[i] - A[j]
memo[i][diff] = 1 + memo[j].get(diff, 1)
#result = max(result, memo[i][diff])
return max(d[diff] for d in memo for diff in d)
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
table = []
for i, z in enumerate(A):
table.append(collections.defaultdict(lambda: 1))
for j in range(i):
diff = z - A[j]
table[i][diff] = table[j][diff] + 1
return max(max(y.values()) for y in table)
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
dp = []
for i, x in enumerate(A):
nd = collections.defaultdict(int)
dp.append(nd)
for j in range(i):
curr_diff = x - A[j]
dp[i][curr_diff] = dp[j][curr_diff] + 1
return max(max(y.values()) for y in dp) + 1
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
dp = dict()
for i in range(len(A)):
for j in range(i):
diff = A[i] - A[j]
if diff not in dp:
dp[diff] = {i: 2}
else:
dic = dp[diff]
if j in dic:
dic[i] = dic[j] + 1
else:
dic[i] = 2
return max(max(v1 for k1, v1 in v.items()) for k, v in dp.items())
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
if len(A)<2: return len(A)
table = []
result = 1
for i, z in enumerate(A):
table.append(collections.defaultdict(lambda: 1))
for j in range(i):
diff = z - A[j]
table[i][diff] = table[j][diff] + 1
#if table[i][diff] > result: result = table[i][diff]
return max([max(y.values()) for y in table])
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
dp = []
for i, x in enumerate(A):
nd = collections.defaultdict(lambda: 1)
dp.append(nd)
for j in range(i):
curr_diff = x - A[j]
dp[i][curr_diff] = dp[j][curr_diff] + 1
return max(max(y.values()) for y in dp)
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
cache = [{} for i in range(len(A))]
n = len(A)
for i in range(1,n):
for j in range(i):
diff = A[i] - A[j]
if diff not in cache[j]:
cache[i][diff] = 2
else:
cache[i][diff] = cache[j][diff] + 1
m = 0
for dictionary in cache:
if dictionary:
m = max(m, max(dictionary.values()))
return m
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
n = len(A)
# out = [1] * n
outdict = {}
longseq = 0
for i in range(n):
for j in range(0, i):
diff = A[i] - A[j]
if diff not in outdict:
outdict[diff] = [1] * n
pointer = outdict[diff]
pointer[i] = max(pointer[i], pointer[j] + 1)
longseq = max(longseq, pointer[i])
# print(longseq)
return longseq
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
memo = [{} for _ in range(len(A))]
for i in range(len(A)):
for j in range(i):
diff = A[i] - A[j]
memo[i][diff] = 1 + memo[j].get(diff, 1)
return max(d[diff] for d in memo for diff in d)
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
d = {}
dd = [{} for i in range(len(A))]
m = 0
for i in range(len(A)):
for j in range(i + 1, len(A)):
diff = A[j] - A[i]
#if diff not in d:
# d[diff] = 0
if diff not in dd[i]:
dd[j][diff] = 1
else:
dd[j][diff] = dd[i][diff] + 1
if dd[j][diff] > m:
m = dd[j][diff]
#d[diff] += 1
#if not d:
# return 0
#print(d)
#return max(d.values()) + 1
return m + 1
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
length = len(A)
onleft = set()
onleftl = []
onright = [0] * 501 #[0 for _ in range(501)]
toextend = [{} for _ in range(501)]
res = 2
for v in A:
onright[v] += 1
for i in range(0, length):
val = A[i]
tex = toextend[val]
onright[val] -= 1
for lval in onleftl:
diff = val - lval
nextval = val + diff
if nextval > 500 or nextval < 0 or onright[nextval] == 0:
continue
if diff in tex:
c = tex[diff] + 1
else:
c = 3
if c > res:
res = c
toextend[nextval][diff] = c
if val not in onleft:
onleftl.append(val)
onleft.add(val)
return res
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
dp = dict()
for i in range(len(A)):
for j in range(i):
diff = A[i] - A[j]
if diff not in dp:
dp[diff] = {i: 2}
else:
dic = dp[diff]
if j in dic:
dic[i] = dic[j] + 1
else:
dic[i] = 2
return max(max(v1 for k1, v1 in list(v.items())) for k, v in list(dp.items()))
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
cache = [{} for i in range(len(A))]
m = 0
n = len(A)
for i in range(1,n):
for j in range(i):
diff = A[i] - A[j]
if diff not in cache[j]:
cache[i][diff] = 2
else:
cache[i][diff] = cache[j][diff] + 1
if cache[i][diff] > m:
m = cache[i][diff]
return m
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
dp = [{} for _ in range(len(A))]
maxSequence = 0
for i in range(len(A)):
for j in range(i):
diff = A[i] - A[j]
dp[i][diff] = val = dp[j].get(diff,1) + 1
if val > maxSequence:
maxSequence = val
return maxSequence
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
dp = []
for i in range(len(A)):
nd = collections.defaultdict(int)
dp.append(nd)
for j in range(i):
curr_diff = A[i] - A[j]
dp[i][curr_diff] = dp[j][curr_diff] + 1
maxVal = -99999
for dt in dp:
maxVal = max(maxVal, max(dt.values()) + 1)
return maxVal
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution(object):
def longestArithSeqLength(self, A):
if not A:
return None
dp = [{} for i in range(0,len(A))]
for i in range(len(A)):
if i == 0:
dp[i][0]= 1
else:
for j in range(0,i):
diff = A[i]-A[j]
if diff in dp[j]:
dp[i][diff] = dp[j][diff]+1
else:
dp[i][diff] = 2
mx = 2
for j in range(len(A)):
for i in dp[j]:
mx = max(dp[j][i],mx)
return mx
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
if not A:
return 0
dp = []
for _ in range(len(A)):
dp.append(dict())
dp[0][0] = 1
for i in range(1, len(A)):
dp[i][0] = 1
for j in range(i):
# continue subsequence
diff = A[i] - A[j]
if diff in dp[j]:
if diff not in dp[i]:
dp[i][diff] = dp[j][diff] + 1
else:
dp[i][diff] = max(dp[i][diff], dp[j][diff] + 1)
# start new subsequence
else:
dp[i][diff] = 2
# for x in dp:
# print(str(x))
return max([max(x.values()) for x in dp])
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
# subsequence problem -> dp
# dp[i][j] -- length of arithmetic subsequence ending at ith and jth element
ans = 2
n = len(A)
index = {}
dp = [[2] * n for i in range(n)]
for i in range(n-1):
for j in range(i+1, n):
first = A[i] * 2 - A[j]
if first in index:
dp[i][j] = dp[index[first]][i] + 1
ans = max(ans, dp[i][j])
index[A[i]] = i
return ans
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
answer = 2
L = len(A)
table = [dict() for _ in range(L)]
for i in range(1, L):
for j in range(0, i):
diff = A[i] - A[j]
if not diff in table[j]:
table[i][diff] = 2
else:
table[i][diff] = table[j][diff] + 1
answer = max(answer, table[i][diff])
return answer
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
# dp[i][j]: for 0-ith elements, the length of subsquence when step = j
# dp[i][j] = dp[i-1][A[i]-A[k]] + 1 where k = 0, 1, ...i-1
# return max(dp[n-1][j])
# base case dp[0][0] = 1
N = len(A)
dp = [{} for _ in range(N)]
for i in range(1, N):
for j in range(0, i):
dp[i][A[i]-A[j]] = dp[j].get(A[i]-A[j], 0) + 1
max_len = 0
for i in range(1, N):
max_len = max(max_len, max(dp[i].values()))
return max_len + 1
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
length = len(A)
onleft = [False for _ in range(501)]
onleftl = []
onright = [0 for _ in range(501)]
toextend = [{} for _ in range(501)]
res = 2
for v in A:
onright[v] += 1
for i in range(0, length):
val = A[i]
tex = toextend[val]
onright[val] -= 1
for lval in onleftl:
diff = val - lval
nextval = val + diff
if nextval > 500 or nextval < 0 or onright[nextval] == 0:
continue
if diff in tex:
c = tex[diff] + 1
else:
c = 3
if c > res:
res = c
toextend[nextval][diff] = c
if not onleft[val]:
onleftl.append(val)
onleft[val] = True
return res
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
if len(A) < 2:
return len(A)
dp = [ {} for i in range(len(A))]
m = 2
for i in range(1, len(A)):
for j in range(0, i):
diff = A[i] - A[j]
if diff in dp[j]:
dp[i][diff] = dp[j][diff]+1
m = max(m, dp[i][diff])
else:
dp[i][diff] = 2
return m
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
dp = []
for _ in range(len(A)):
dp.append({})
max_ = 0
dp[0][0] = 1
for i in range(1, len(A)):
for j in range(0, i):
diff = A[i] - A[j]
if diff in dp[j]:
dp[i][diff] = dp[j][diff] + 1
else:
dp[i][diff] = 2
if dp[i][diff] > max_:
max_ = dp[i][diff]
return max_
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
'''
9 4 7 2 10
-5 4 2 -5 2 8
-2 2 -2 3 3
-7 2 6
1
j i
could sort array.
could iterate through jump sizes
could transition each elem to distance from other.
'''
if len(A) < 3:
return len(A)
best = 2
sequences = [ {} for _ in A]
for right in range(1, len(A)):
for left in range(right):
diff = A[right] - A[left]
#print(diff, sequences[left])
if diff in sequences[left]:
count = sequences[left][diff] + 1
sequences[right][diff] = count
best = max(best, count)
else:
sequences[right][diff] = 2
return best
'''
best = 2
for i in range(len(A)-2):
for j in range(len(A)-1):
jump = A[j] - A[i]
last = A[j]
thisCount = 2
for k in range(j+1, len(A)):
if A[k] == last + jump:
thisCount += 1
last = A[k]
best = max(best, thisCount)
return best
'''
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
if len(A) == 1:
return 1
max_l = 2
dp = [{0: 1}]
for i in range(1, len(A)):
dp.append({})
for j in range(0, i):
idx = A[i] -A[j]
if idx in dp[j]:
dp[i][idx] = dp[j][idx] + 1
max_l = max(max_l, dp[i][idx])
else:
dp[i][idx] = 2
return max_l
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
from collections import defaultdict
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
'''
# Note:
A.length >= 2
# Analysis:
Arithmetic sequence
'''
n = len(A)
res = 2
dif_arr = [defaultdict(int) for _ in range(n)]
for i in range(1, n):
for j in range(i):
dif = A[i] - A[j]
if dif in dif_arr[j]:
dif_arr[i][dif] = dif_arr[j][dif] + 1
res = max(res, dif_arr[i][dif]+1)
else:
dif_arr[i][dif] = 1
return res
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
if len(A) < 2:
return len(A)
dp = [ {} for i in range(len(A))]
m = 2
for i in range(1, len(A)):
for j in range(0, i):
diff = A[i] - A[j]
if diff in dp[j]:
dp[i][diff] = dp[j][diff]+1
m = max(m, dp[i][diff])
else:
if diff not in dp[i]:
dp[i][diff] = 2
return m
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
from collections import defaultdict
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
# mapping: idx -> (mapping: arithmetic_step -> longest_arithmetic_subsequence_with_this_step_ending_at_idx
d = defaultdict(lambda: defaultdict(lambda: 1))
for i,a in enumerate(A):
# LAS: A[i]
d[i][0] = 1
for j in range(i):
# Consider each subsequence that ends at i ~ A[?] ... A[??] A[j] A[i]
# A[i] - A[j] denotes the step
# LSA(j, step) := length of LSA ending at j with progression equal to step
# We only care about count, not the actual sequence, so length of such subsequence will be: 1 + LSA(j, step)
step = A[i] - A[j]
d[i][step] = d[j][step] + 1
return max([max(dn.values()) for dn in d.values()])
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
# d subproblem
# index, difference
D = []
for i in range(1001):
D.append([0]* 1002) # first 501 is pos, second 501 is neg difference
best = 0
for second in range(len(A)-1, -1, -1):
for first in range(second-1, -1, -1):
diff = A[second]-A[first]
if diff < 0:
diff = 500 + -1 * diff
D[first][diff] = D[second][diff] + 1
if D[first][diff] > best:
best = D[first][diff]
# print(f'best: {best}, first: {first}, diff: {diff}')
# print(D[0][501+5])
return best + 1
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
from collections import defaultdict
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
# mapping:
d = defaultdict(lambda: defaultdict(lambda: 1))
for i,a in enumerate(A):
d[i][0] = 1
for j in range(i):
step = A[i] - A[j]
d[i][step] = d[j][step] + 1
return max([max(dn.values()) for dn in d.values()])
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
from itertools import repeat
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
length = len(A)
onleft = 0
onleftl = []
onright = {}
toextend = [{} for _ in range(501)]
res = 2
for v in A:
onright[v] = onright.get(v, 0) + 1
for i in range(0, length):
val = A[i]
tex = toextend[val]
onright[val] -= 1
for lval in onleftl:
diff = val - lval
nextval = val + diff
if onright.get(nextval, 0) == 0:
continue
if diff in tex:
c = tex[diff] + 1
else:
c = 3
if c > res:
res = c
toextend[nextval][diff] = c
b = (1<<val)
if not (onleft & b):
onleftl.append(val)
onleft = (onleft | b)
return res
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
memo = {} # storing next Item -> (diff pattern, length so far)
# [a, b, c]
maxLength = 2
if len(A) < 3:
return len(A)
for i in range(len(A)): # iterating over A
if A[i] in memo:
toIter = [(i, j) for i, j in list(memo[A[i]].items())]
del memo[A[i]]
for k in toIter:
diff, length = k
if length > maxLength:
maxLength = length
length += 1
newKey = A[i] + diff
if newKey not in memo:
memo[newKey] = {}
if diff in memo[newKey]:
memo[newKey][diff] = max(length, memo[newKey][diff])
else:
memo[newKey][diff] = length
for j in range(i):
diff = A[i] - A[j]
newKey = A[i] + diff
if A[i] + diff not in memo:
memo[newKey] = {}
if diff not in memo[newKey]:
memo[newKey][diff] = 3
return maxLength
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
dp = [defaultdict(int) for a in A]
for i,a in enumerate(A):
for j in range(i):
dp[i][a-A[j]]=dp[j][a-A[j]]+1
#print(dp)
m = 0
for d in dp:
x = d.values()
if x: m=max(m, max(x))
return m+1
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
dp = {}
for i in range(1, len(A)):
item = A[i]
for j in range(0, i):
d = item - A[j]
if (j, d) in dp:
dp[i, d] = dp[j, d] + 1
else:
dp[i, d] = 2
return max(dp.values())
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
d = collections.defaultdict(dict)
n = len(A)
res = 1
for i in range(n):
for j in range(i):
v = A[i] - A[j]
if v not in d[j]: d[j][v] = 1
if v not in d[i]: d[i][v] = 0
d[i][v] = max(d[i][v] ,d[j][v] + 1)
res = max(res, d[i][v])
return res
|
Given an array A of integers, return the length of the longest arithmetic subsequence in A.
Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).
Example 1:
Input: A = [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.
Example 2:
Input: A = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
Example 3:
Input: A = [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].
Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
|
from collections import defaultdict
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
d = defaultdict(lambda: defaultdict(lambda: 1))
for i,a in enumerate(A):
d[a][0] = 1
for j in range(i):
d[a][A[i] - A[j]] = d[A[j]][A[i]-A[j]] + 1
return max([max(dn.values()) for dn in d.values()])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.