inputs
stringlengths 50
14k
| targets
stringlengths 4
655k
|
|---|---|
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
Example:
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
|
class Solution:
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# init dict, set default to 0
length_dict = {key: 0 for key in nums}
longest = 0
for i in nums:
#print("i = "+str(i))
if length_dict[i]:
#print("skip "+str(i)) # already done
continue
length = 1
length_dict[i] = 1
#print(length_dict)
j = i + 1
while j in length_dict:
#print("+:"+str(j))
length_dict[j] = 1
length += 1
j += 1
j = i - 1
while j in length_dict:
#print("-:"+str(j))
length_dict[j] = 1
length += 1
j -= 1
longest = max(longest, length)
return longest
|
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
Example:
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
|
class Solution:
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 0:
return 0
seen = set()
heads = set()
tails = set()
forward = dict()
reverse = dict()
for n in nums:
if n in seen:
continue
else:
seen.add(n)
if n-1 not in tails and n+1 not in heads:
heads.add(n)
tails.add(n)
forward[n] = n
reverse[n] = n
if n-1 not in tails and n+1 in heads:
heads.remove(n+1)
heads.add(n)
tail = forward[n+1]
del forward[n+1]
forward[n] = tail
reverse[tail] = n
if n-1 in tails and n+1 not in heads:
tails.remove(n-1)
tails.add(n)
head = reverse[n-1]
del reverse[n-1]
reverse[n] = head
forward[head] = n
if n-1 in tails and n+1 in heads:
head = reverse[n-1]
tail = forward[n+1]
heads.remove(n+1)
tails.remove(n-1)
del forward[n+1]
del reverse[n-1]
forward[head] = tail
reverse[tail] = head
diffs = [v - k + 1 for (k,v) in list(forward.items())]
maxRun = max(diffs)
return maxRun
|
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
Example:
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
|
class Solution:
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
flag_map = {}
for x in nums:
flag_map[x] = False
result = 0
for x in nums:
count = 1
tmp = x + 1
flag_map[x] = True
while True:
if tmp in flag_map and not flag_map[tmp]:
count = count + 1
flag_map[tmp] = True
tmp = tmp + 1
else:
break
tmp = x - 1
while True:
if tmp in flag_map and not flag_map[tmp]:
count = count + 1
flag_map[tmp] = True
tmp = tmp - 1
else:
break
result = max(result, count)
return result
|
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
Example:
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
|
class Solution:
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
from collections import Counter
def find(x,maps):
if x in maps:
maps[x]=find(maps[x],maps)
else:
return x
return maps[x]
def join(x,y,maps):
i,j=find(x,maps),find(y,maps)
if i!=j:
if i<j:
maps[j]=i
else:
maps[i]=j
if not nums:
return 0
visited={}
maps={}
for i in nums:
if i in visited:
continue
if i not in visited and i-1 in visited:
join(i-1,i,maps)
if i not in visited and i+1 in visited:
join(i+1,i,maps)
if i not in visited:
visited[i]=1
if not maps:
return 1
for key in list(maps.keys()):
join(maps[key],key,maps)
d=Counter(list(maps.values()))
return max(d.values())+1
|
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
Example:
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
|
class Solution:
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums = set(nums)
best = 0
for x in nums:
if x - 1 not in nums:
y = x + 1
while y in nums:
y += 1
best = max(best, y - x)
return best
|
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
Example:
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
|
class Solution:
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
s = set(nums)
longest = 0
for i in s:
if(i-1 in s):
continue
sequence = 1
num = i
while(num+1 in s):
sequence += 1
num += 1
longest = max(longest, sequence)
return longest
|
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
Example:
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
|
class Solution:
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max_count = 0
s = set(nums)
for i in nums:
cnt = 1
tmp = i-1
while tmp in s:
cnt += 1
s.discard(tmp)
tmp -= 1
tmp = i+1
while tmp in s:
cnt += 1
s.discard(tmp)
tmp += 1
max_count = max(max_count, cnt)
return max_count
|
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
Example:
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
|
class Solution:
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
longest = 1
current = 1
nums.sort()
n = len(nums)
for i in range(1, n):
if nums[i] != nums[i-1]:
if nums[i] == nums[i-1] + 1:
current += 1
else:
longest = max(longest, current)
current = 1
return max(longest, current)
|
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
Example:
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
|
class Solution(object):
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
nums_set = set(nums) # dedup and build a map for fast lookup
# remove numbers which are not connected with any other numbers
for num in list(nums_set):
if (num - 1) not in nums_set and (num + 1) not in nums_set:
nums_set.remove(num)
# now nums_set only contains groups of consecutive numbers
# calculate the size of each group and find the largest group
max_group_size = 1
while nums_set:
num = nums_set.pop()
group_size = 1
prev_num = num - 1
while prev_num in nums_set:
group_size += 1
nums_set.remove(prev_num)
prev_num -= 1
next_num = num + 1
while next_num in nums_set:
group_size += 1
nums_set.remove(next_num)
next_num += 1
if group_size > max_group_size:
max_group_size = group_size
return max_group_size
|
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
Example:
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
|
class Solution:
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
max_length = 0
count =0
for idx, v in enumerate(nums):
if count==0:
count+=1
max_length=max(max_length,count)
if idx+1<len(nums):
n_v = nums[idx+1]
if n_v==v+1:
count=count+1
elif n_v==v:
continue
else:
max_length=max(max_length,count)
count = 0
#deal with the end
max_length=max(max_length,count)
return max_length
|
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
Example:
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
|
class Solution:
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def union(uf, p, q):
i, j = root(uf, p), root(uf, q)
uf[i], uf[j] = min(i, j), min(i, j)
def root (uf, p):
while p != uf[p]:
uf[p] = uf[uf[p]]
p = uf[p]
return p
if len(nums) == 0:
return 0
ht = {}
uf = [i for i in range(len(nums))]
for i, n in enumerate(nums):
if n not in ht:
ht[n] = i
else:
continue
m, o = n - 1, n + 1
if m in ht:
union(uf, ht[m], i)
if o in ht:
union(uf, ht[o], i)
roots = {}
for x in uf:
r = root(uf, x)
if r in roots:
roots[r] += 1
else:
roots[r] = 1
return max(roots.values())
|
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
Example:
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
|
class Solution:
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# unique elms in list
elms = set()
# prevent dup. effort during consecutive search
visited = set()
max_consecutive = 0
for num in nums:
elms.add(num)
# look for all unique consecutive subsequences
for num in nums:
if num in visited:
continue
visited.add(num)
# elm by itself
curr_consecutive = 1
tmp = num - 1
# number of consecutive elms before
# this elm
while tmp in elms:
visited.add(tmp)
curr_consecutive += 1
tmp -= 1
tmp = num + 1
# number of consecutive elms after
# this elm
while tmp in elms:
visited.add(tmp)
curr_consecutive += 1
tmp += 1
if curr_consecutive > max_consecutive:
max_consecutive = curr_consecutive
return max_consecutive
|
Given an integer k, return the minimum number of Fibonacci numbers whose sum is equal to k. The same Fibonacci number can be used multiple times.
The Fibonacci numbers are defined as:
F1 = 1
F2 = 1
Fn = Fn-1 + Fn-2 for n > 2.
It is guaranteed that for the given constraints we can always find such Fibonacci numbers that sum up to k.
Example 1:
Input: k = 7
Output: 2
Explanation: The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ...
For k = 7 we can use 2 + 5 = 7.
Example 2:
Input: k = 10
Output: 2
Explanation: For k = 10 we can use 2 + 8 = 10.
Example 3:
Input: k = 19
Output: 3
Explanation: For k = 19 we can use 1 + 5 + 13 = 19.
Constraints:
1 <= k <= 10^9
|
class Solution:
def findMinFibonacciNumbers(self, k: int) -> int:
fib = [1, 1] # initializing a Fibonacci table with F[0] and F[1]
i = 1 # index that will represent the last filled index of table
temp = fib[0] + fib[1] # initial value of values to be appended
while temp < k: # we keep filling table until temp >= k
fib.append(temp) # add the current value to the table
i += 1 # increase i by 1 to keep track of the last filled index
temp = fib[i] + fib[i-1] # calculate new temp
fib.append(temp) # to cover case temp == k, we append the last value >= k
ans = 0 # initializing answer value with 0
j = -1 # placeholder to represent last checked Fibonacci table index
while k > 0: # keep repeating until k <= 0
temp = fib[j] # get the biggest number available
j -= 1 # decrease j by 1 since we tried the last number
if temp <= k:
ans+=1
k-=temp
return ans
|
Given an integer k, return the minimum number of Fibonacci numbers whose sum is equal to k. The same Fibonacci number can be used multiple times.
The Fibonacci numbers are defined as:
F1 = 1
F2 = 1
Fn = Fn-1 + Fn-2 for n > 2.
It is guaranteed that for the given constraints we can always find such Fibonacci numbers that sum up to k.
Example 1:
Input: k = 7
Output: 2
Explanation: The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ...
For k = 7 we can use 2 + 5 = 7.
Example 2:
Input: k = 10
Output: 2
Explanation: For k = 10 we can use 2 + 8 = 10.
Example 3:
Input: k = 19
Output: 3
Explanation: For k = 19 we can use 1 + 5 + 13 = 19.
Constraints:
1 <= k <= 10^9
|
class Solution:
def findMinFibonacciNumbers(self, k: int) -> int:
a = b = 1
fibo = [a,b]
res = 0
while a + b <= k:
fibo.append(a + b)
a, b = b, a+b
for i in fibo[::-1]:
if k >= i:
k -= i
res +=1
return res
|
Given an integer k, return the minimum number of Fibonacci numbers whose sum is equal to k. The same Fibonacci number can be used multiple times.
The Fibonacci numbers are defined as:
F1 = 1
F2 = 1
Fn = Fn-1 + Fn-2 for n > 2.
It is guaranteed that for the given constraints we can always find such Fibonacci numbers that sum up to k.
Example 1:
Input: k = 7
Output: 2
Explanation: The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ...
For k = 7 we can use 2 + 5 = 7.
Example 2:
Input: k = 10
Output: 2
Explanation: For k = 10 we can use 2 + 8 = 10.
Example 3:
Input: k = 19
Output: 3
Explanation: For k = 19 we can use 1 + 5 + 13 = 19.
Constraints:
1 <= k <= 10^9
|
class Solution:
def findMinFibonacciNumbers(self, k: int) -> int:
f = []
f.append(1)
f.append(1)
while 1:
if max(f) <= k:
f.append(f[len(f)-1] + f[len(f)-2])
else:
break
f.remove(f[len(f)-1])
number = 0
while k != 0:
if f[len(f)-1] <= k:
k -= f[len(f)-1]
f.remove(max(f))
number += 1
else:
f.remove(max(f))
return number
|
Given an integer k, return the minimum number of Fibonacci numbers whose sum is equal to k. The same Fibonacci number can be used multiple times.
The Fibonacci numbers are defined as:
F1 = 1
F2 = 1
Fn = Fn-1 + Fn-2 for n > 2.
It is guaranteed that for the given constraints we can always find such Fibonacci numbers that sum up to k.
Example 1:
Input: k = 7
Output: 2
Explanation: The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ...
For k = 7 we can use 2 + 5 = 7.
Example 2:
Input: k = 10
Output: 2
Explanation: For k = 10 we can use 2 + 8 = 10.
Example 3:
Input: k = 19
Output: 3
Explanation: For k = 19 we can use 1 + 5 + 13 = 19.
Constraints:
1 <= k <= 10^9
|
class Solution:
def findMinFibonacciNumbers(self, k: int) -> int:
first = 1
second = 1
fib = []
i = 0
while True:
if i == 0:
fib.append(1)
elif i == 1:
fib.append(1)
else:
val = fib[i - 1] + fib[i - 2]
if val > k: break
fib.append(val)
i += 1
print(fib)
accum = 0
ct = 0
for i in range(len(fib) - 1, -1 , -1):
accum += fib[i]
if accum == k:
ct += 1
break
elif accum > k:
accum -= fib[i]
else:
ct += 1
return ct
|
Given an integer k, return the minimum number of Fibonacci numbers whose sum is equal to k. The same Fibonacci number can be used multiple times.
The Fibonacci numbers are defined as:
F1 = 1
F2 = 1
Fn = Fn-1 + Fn-2 for n > 2.
It is guaranteed that for the given constraints we can always find such Fibonacci numbers that sum up to k.
Example 1:
Input: k = 7
Output: 2
Explanation: The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ...
For k = 7 we can use 2 + 5 = 7.
Example 2:
Input: k = 10
Output: 2
Explanation: For k = 10 we can use 2 + 8 = 10.
Example 3:
Input: k = 19
Output: 3
Explanation: For k = 19 we can use 1 + 5 + 13 = 19.
Constraints:
1 <= k <= 10^9
|
class Solution:
def findMinFibonacciNumbers(self, k: int) -> int:
grid = [1,1]
last = 1
while last < k:
target = grid[-1] + grid[-2]
if target > k: break
else:
grid.append(grid[-1] + grid[-2])
last = grid[-1]
res = 0
ends = len(grid)-1
while k > 0:
while grid[ends] > k: ends -= 1
k -= grid[ends]
ends -= 1
res += 1
return res
|
Given an integer k, return the minimum number of Fibonacci numbers whose sum is equal to k. The same Fibonacci number can be used multiple times.
The Fibonacci numbers are defined as:
F1 = 1
F2 = 1
Fn = Fn-1 + Fn-2 for n > 2.
It is guaranteed that for the given constraints we can always find such Fibonacci numbers that sum up to k.
Example 1:
Input: k = 7
Output: 2
Explanation: The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ...
For k = 7 we can use 2 + 5 = 7.
Example 2:
Input: k = 10
Output: 2
Explanation: For k = 10 we can use 2 + 8 = 10.
Example 3:
Input: k = 19
Output: 3
Explanation: For k = 19 we can use 1 + 5 + 13 = 19.
Constraints:
1 <= k <= 10^9
|
class Solution:
def findMinFibonacciNumbers(self, k: int) -> int:
if k < 2:
return k
f1, f2 = 1, 1
while f2 <= k:
f1, f2 = f2, f1 + f2
t = 0
while k:
# print(f1, f2, k, t)
if f2 <= k:
k -= f2
t += 1
else:
f1, f2 = f2 - f1, f1
return t
|
Given an integer k, return the minimum number of Fibonacci numbers whose sum is equal to k. The same Fibonacci number can be used multiple times.
The Fibonacci numbers are defined as:
F1 = 1
F2 = 1
Fn = Fn-1 + Fn-2 for n > 2.
It is guaranteed that for the given constraints we can always find such Fibonacci numbers that sum up to k.
Example 1:
Input: k = 7
Output: 2
Explanation: The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ...
For k = 7 we can use 2 + 5 = 7.
Example 2:
Input: k = 10
Output: 2
Explanation: For k = 10 we can use 2 + 8 = 10.
Example 3:
Input: k = 19
Output: 3
Explanation: For k = 19 we can use 1 + 5 + 13 = 19.
Constraints:
1 <= k <= 10^9
|
class Solution:
def findMinFibonacciNumbers(self, k: int) -> int:
a,b = 1,1
while b<=k:
a,b = b, a+b
res = 0
while a > 0:
if k >= a:
k -= a
res += 1
a,b = b-a, a
return res
# if k == 0:
# return 0
# a,b = 1, 1
# while b <= k: # O( (logk)^2 )
# a,b = b, a+b
# return self.findMinFibonacciNumbers(k-a)+1
# First recursion, logk. Second resursion logK - 1, third entry logK - 2.
# arr = [1, 1]
# while arr[-1] <= k:
# arr.append( arr[-1]+arr[-2] ) # O(n) space
# d = k-arr[-2]
# cnt = 1
# while d > 0:
# ind = bisect.bisect_right(arr, d) # O(n log n)
# d -= arr[ind-1]
# cnt += 1
# return cnt
|
Given an integer k, return the minimum number of Fibonacci numbers whose sum is equal to k. The same Fibonacci number can be used multiple times.
The Fibonacci numbers are defined as:
F1 = 1
F2 = 1
Fn = Fn-1 + Fn-2 for n > 2.
It is guaranteed that for the given constraints we can always find such Fibonacci numbers that sum up to k.
Example 1:
Input: k = 7
Output: 2
Explanation: The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ...
For k = 7 we can use 2 + 5 = 7.
Example 2:
Input: k = 10
Output: 2
Explanation: For k = 10 we can use 2 + 8 = 10.
Example 3:
Input: k = 19
Output: 3
Explanation: For k = 19 we can use 1 + 5 + 13 = 19.
Constraints:
1 <= k <= 10^9
|
class Solution:
def findMinFibonacciNumbers(self, k: int) -> int:
fibo=[]
fibo.append(1)
fibo.append(1)
lenn=2
while fibo[-1]<=k:
fibo.append(fibo[lenn-1]+fibo[lenn-2])
lenn+=1
nums=k
cnt=0
for i in range(len(fibo)-1, -1, -1):
while nums>=fibo[i]:
nums-=fibo[i]
cnt+=1
if nums==0:
break
return cnt
|
Given an integer k, return the minimum number of Fibonacci numbers whose sum is equal to k. The same Fibonacci number can be used multiple times.
The Fibonacci numbers are defined as:
F1 = 1
F2 = 1
Fn = Fn-1 + Fn-2 for n > 2.
It is guaranteed that for the given constraints we can always find such Fibonacci numbers that sum up to k.
Example 1:
Input: k = 7
Output: 2
Explanation: The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ...
For k = 7 we can use 2 + 5 = 7.
Example 2:
Input: k = 10
Output: 2
Explanation: For k = 10 we can use 2 + 8 = 10.
Example 3:
Input: k = 19
Output: 3
Explanation: For k = 19 we can use 1 + 5 + 13 = 19.
Constraints:
1 <= k <= 10^9
|
class Solution:
def findMinFibonacciNumbers(self, k: int) -> int:
if k == 0:
return 0
a,b = 1, 1
while b <= k:
a,b = b, a+b
return self.findMinFibonacciNumbers(k-a)+1
# arr = [1, 1]
# while arr[-1] <= k:
# arr.append( arr[-1]+arr[-2] ) # O(n) space
# d = k-arr[-2]
# cnt = 1
# while d > 0:
# ind = bisect.bisect_right(arr, d) # O(n log n)
# d -= arr[ind-1]
# cnt += 1
# return cnt
|
Given an integer k, return the minimum number of Fibonacci numbers whose sum is equal to k. The same Fibonacci number can be used multiple times.
The Fibonacci numbers are defined as:
F1 = 1
F2 = 1
Fn = Fn-1 + Fn-2 for n > 2.
It is guaranteed that for the given constraints we can always find such Fibonacci numbers that sum up to k.
Example 1:
Input: k = 7
Output: 2
Explanation: The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ...
For k = 7 we can use 2 + 5 = 7.
Example 2:
Input: k = 10
Output: 2
Explanation: For k = 10 we can use 2 + 8 = 10.
Example 3:
Input: k = 19
Output: 3
Explanation: For k = 19 we can use 1 + 5 + 13 = 19.
Constraints:
1 <= k <= 10^9
|
class Solution:
def findMinFibonacciNumbers(self, k: int) -> int:
count=0
while(k>=0):
arr=[]
arr.append(1)
arr.append(1)
while(arr[-1]+arr[-2]<=k):
arr.append(arr[-1]+arr[-2])
k-=arr[-1]
count+=1
return count-1
|
Given an integer k, return the minimum number of Fibonacci numbers whose sum is equal to k. The same Fibonacci number can be used multiple times.
The Fibonacci numbers are defined as:
F1 = 1
F2 = 1
Fn = Fn-1 + Fn-2 for n > 2.
It is guaranteed that for the given constraints we can always find such Fibonacci numbers that sum up to k.
Example 1:
Input: k = 7
Output: 2
Explanation: The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ...
For k = 7 we can use 2 + 5 = 7.
Example 2:
Input: k = 10
Output: 2
Explanation: For k = 10 we can use 2 + 8 = 10.
Example 3:
Input: k = 19
Output: 3
Explanation: For k = 19 we can use 1 + 5 + 13 = 19.
Constraints:
1 <= k <= 10^9
|
class Solution:
def findMinFibonacciNumbers(self, k: int) -> int:
fib = [1,1]
while(fib[-1]<k):
fib.append(fib[-1]+fib[-2])
print(fib)
if k in fib:
return 1
cnt =0
for i in range(len(fib)-1,-1,-1):
print(('cnt ',cnt,'i ',i, fib[i],'k ',k))
if fib[i]<=k:
k = k-fib[i]
cnt+=1
if k==0:
break
return cnt
|
Given an integer k, return the minimum number of Fibonacci numbers whose sum is equal to k. The same Fibonacci number can be used multiple times.
The Fibonacci numbers are defined as:
F1 = 1
F2 = 1
Fn = Fn-1 + Fn-2 for n > 2.
It is guaranteed that for the given constraints we can always find such Fibonacci numbers that sum up to k.
Example 1:
Input: k = 7
Output: 2
Explanation: The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ...
For k = 7 we can use 2 + 5 = 7.
Example 2:
Input: k = 10
Output: 2
Explanation: For k = 10 we can use 2 + 8 = 10.
Example 3:
Input: k = 19
Output: 3
Explanation: For k = 19 we can use 1 + 5 + 13 = 19.
Constraints:
1 <= k <= 10^9
|
class Solution:
def findMinFibonacciNumbers(self, k: int) -> int:
fib = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610,
987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368,
75025, 121393, 196418, 317811, 514229, 832040, 1346269,
2178309, 3524578, 5702887, 9227465, 14930352, 24157817,
39088169, 63245986, 102334155, 165580141, 267914296,
433494437, 701408733]
ans = 0
j= -1
while k>0:
tmp = fib[j]
j-=1
if tmp<=k:
ans+=1
k-=tmp
return ans
|
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
Example:
Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST's:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
|
class Solution:
hash = {}
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
# return base case
if n == 0:
return 1
if n == 1 or n == 2:
return n
# try fetching from hash
try:
return self.hash[n]
except KeyError:
pass
# holds the sum
resSum = 0
# iterate i from 1 to n-1
# should add up (0,4), (1,3), (2,2), (3,1), (4,0)
for i in range(n):
#print(i,n - (i+1))
tempSum = self.numTrees(i) * self.numTrees(n - (i+1))
#print(tempSum)
resSum += tempSum
# append to hash
self.hash[n]=resSum
return resSum
|
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
Example:
Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST's:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
|
class Solution:
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
res = [0] * (n+1)
res[0] = res[1] = 1
for i in range(2,n+1):
for j in range(1,i+1):
res[i] += res[j-1] * res[i-j]
return res[-1]
|
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
Example:
Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST's:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
|
class Solution:
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
if n<1:
return 1
tree_nums = [0]*(n+1)
tree_nums[0] = 1
tree_nums[1] = 1 # index start with 1
for t in range(2, n+1):
for root in range(1,t+1):
lt_num = root-1 # nodes num which smaller than root
rt_num = t-root # nodes num which larger than root
tree_nums[t] += tree_nums[lt_num]*tree_nums[rt_num]
return tree_nums[n]
|
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
Example:
Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST's:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
|
class Solution:
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
dp = [0]*(n+1)
dp[0] = dp[1] = 1
for i in range(2, n+1):
total = 0
for j in range(i):
total += (dp[j] * dp[i-j-1])
dp[i] = total
return dp[n]
|
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
Example:
Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST's:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
|
class Solution:
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
"""
The most straightforward solution would be to try all possible permutations that specify the order of input in constructing a BST and counting the different ways in which the BST results. But that would take O(n!) time and O(n) space.
Maybe it would help to use the fact that a BST is defined recursively.
Does the topology of a subtree affects whether the parent subtree is valid or not?
No.
And is it possible that we get any duplicate trees when we first designate our root and then permute its subtrees?
No.
So for each node i, set i as a root and then construct/permute the left and the right subtrees.
The parameter we need to take care of is the list of available nodes in that subtree.
Memoize the results, too.
"""
def memoize(func):
func.cache = cache = dict()
def memoizer(*args):
key = str(args)
if key not in cache:
cache[key] = func(*args)
return cache[key]
return memoizer
@memoize
def count(root, lower_bound, upper_bound):
if upper_bound < lower_bound:
return 0
if lower_bound == upper_bound:
return 1
left_combinations = max(1, sum(count(left, lower_bound, root - 1) for left in range(lower_bound, root)))
right_combinations = max(1, sum(count(right, root + 1, upper_bound) for right in range(root + 1, upper_bound + 1)))
#print(root, lower_bound, upper_bound, left_combinations, right_combinations)
return left_combinations * right_combinations
return sum(count(root, 1, n) for root in range(1, n + 1))
|
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
Example:
Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST's:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
|
class Solution:
from functools import lru_cache
@lru_cache(maxsize=None)
def numTrees(self, high, low=1, depth=0):
"""
:type n: int
:rtype: int
"""
return sum(self.numTrees(key - 1, low, depth + 1) * self.numTrees(high, key + 1, depth + 1) for key in range(low, high + 1)) or 1
|
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
Example:
Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST's:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
|
class Solution:
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
nums = [0] * (n+1)
nums[0] = 1
nums[1] = 1
for i in range(2, n+1):
for j in range(i):
nums[i] += nums[j] * nums[i - j - 1]
return nums[n]
|
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
Example:
Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST's:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
|
class Solution:
def numTrees(self, n):
dp = [0] * (n + 1)
dp[0] = 1
for i in range(1, n + 1):
for j in range(i):
print(j)
print((i - j - 1))
dp[i] += dp[j] * dp[i - j - 1]
return dp[-1]
"""
:type n: int
:rtype: int
"""
|
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
Example:
Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST's:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
|
class Solution:
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
a = [1]
i = 1
while i < n:
tmp = [sum(a), sum(a)]
for j in range(len(a) - 1):
tmp.append(tmp[j + 1] - a[j])
i += 1
a = tmp
return sum(a)
|
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
Example:
Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST's:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
|
class Solution:
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
dp = [1, 1, 2]
if n < 3:
return dp[n]
for i in range(3, n + 1):
dp.append(sum(dp[j - 1] * dp[i - j] for j in range(1, i + 1)))
return dp[n]
|
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
Example:
Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST's:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
|
class Solution:
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
dp = [0 for _ in range(n+1)]
dp[1] = 1
dp[0] = 1
for x in range(2, n+1):
for y in range(1, x+1):
dp[x] += (dp[y - 1] * dp[x-y])
return dp[-1]
|
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
Example:
Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST's:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
|
class Solution:
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
if n <= 1:
return 1
dp = [1 for i in range(n+1)]
for i in range(2, n+1):
sums = 0
for j in range(1, i+1):
sums += dp[j-1] * dp[i-j]
dp[i] = sums
print(dp)
return dp[-1]
|
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
Example:
Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST's:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
|
class Solution:
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
M = [0 for x in range(n)]
M[0] = 1
for i in range(1,n):
for j in range(1,i):
M[i] += M[j-1] * M[i-j-1]
M[i] += M[i-1] * 2
return M[n-1]
|
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
Example:
Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST's:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
|
class Solution:
from functools import lru_cache
@lru_cache(maxsize=None)
def numTrees(self, high, low=1):
"""
:type n: int
:rtype: int
"""
return sum(self.numTrees(key - 1, low) * self.numTrees(high, key + 1) for key in range(low, high + 1)) or 1
|
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
Example:
Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST's:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
|
class Solution:
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
G = [0 for _ in range(n+1)]
G[0] = 1
G[1] = 1
for i in range(2, n+1):
for j in range(i+1):
G[i] += G[j-1]*G[i-j]
return G[-1]
|
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
|
class Solution:
def longestMountain(self, A: List[int]) -> int:
up=0
down=0
ans=0
for i in range(0,len(A)-1):
if A[i]<A[i+1]:
if down==0:
up+=1
else:
up=1
down=0
elif A[i]>A[i+1]:
if up>0:
down+=1
mountain=up+down+1
if ans<mountain:
ans=mountain
else:
up=0
down=0
return ans
|
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
|
class Solution:
def longestMountain(self, A: List[int]) -> int:
leftpivot = 0
rightpivot = 0
ascendign = False
descending = False
changes = 0
highest = 0
while(leftpivot<len(A)):
rightpivot=leftpivot
if(rightpivot+1 < len(A) and A[rightpivot]<A[rightpivot+1]):
while(rightpivot + 1<len(A) and A[rightpivot]<A[rightpivot+1] ):
rightpivot+=1
if(rightpivot + 1<len(A) and A[rightpivot]>A[rightpivot+1]):
while(rightpivot<(len(A)-1) and A[rightpivot]>A[rightpivot+1]):
rightpivot+=1
highest = max(highest,rightpivot+1-leftpivot)
leftpivot = max(rightpivot,leftpivot+1)
return highest
|
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
|
class Solution:
def longestMountain(self, A: List[int]) -> int:
if len(A) < 3:
return 0
prev_height = None
peaks = [0 for _ in range(len(A))]
has_increment = False
# combs left to right for peaks
for idx in range(len(A)):
if prev_height is not None:
if prev_height < A[idx]:
peaks[idx] = peaks[idx-1] + 1
has_increment = True
else:
if has_increment:
peaks[idx-1] += 1
peaks[idx] = 0
has_increment = False
prev_height = A[idx]
print(peaks)
# combs right to left for peaks
prev_height = None
max_so_far = 0
has_increment = False
for idx in range(len(A)-1, -1, -1):
if prev_height is not None:
if prev_height < A[idx]:
peaks[idx] += peaks[idx+1] + 1
has_increment = True
else:
if has_increment and prev_height > A[idx]:
max_so_far = max(max_so_far, peaks[idx+1])
peaks[idx] = peaks[idx]
has_increment = False
prev_height = A[idx]
print(peaks)
return max_so_far
|
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
|
class Solution:
def longestMountain(self, A: List[int]) -> int:
if len(A) < 3:
return 0
n = len(A)
ups, downs = [0] * n, [0] * n
i, j = 0, n - 1
while i < n - 1:
if A[i] < A[i+1]:
ups[i+1] = ups[i] + 1
i += 1
while j > 0:
if A[j] < A[j-1]:
downs[j-1] = downs[j] + 1
j -= 1
print((ups, downs))
longest = [u + d + 1 for u, d in zip(ups, downs) if u and d]
return max(longest) if longest else 0
|
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
|
class Solution:
def longestMountain(self, A: List[int]) -> int:
N = len(A)
prefix = [1] * N
suffix = [1] * N
for i, num in enumerate(A[1:], 1):
i_rev = N - i - 1
prefix[i] = prefix[i-1] + 1 if A[i-1] < num else 1
suffix[i_rev] = suffix[i_rev+1] + 1 if A[i_rev] > A[i_rev+1] else 1
ans = 0
for i, num in enumerate(A):
left = prefix[i]
right = suffix[i]
length = left + right - 1
if length >= 3 and min(left, right) > 1:
ans = max(ans, length)
return ans
|
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
|
class Solution:
def longestMountain(self, A: List[int]) -> int:
leftIncreasing = [0 for x in range(len(A))]
rightIncreasing = [0 for x in range(len(A))]
for x in range(1, len(A)):
if A[x] > A[x - 1]:
leftIncreasing[x] += (leftIncreasing[x - 1] + 1)
if A[len(A) - 1 - x] > A[len(A) - x]:
rightIncreasing[len(A) - 1 - x] += (rightIncreasing[len(A) - x] + 1)
result = 0
for x in range(len(A)):
if leftIncreasing[x] and rightIncreasing[x]:
result = max(result, leftIncreasing[x] + rightIncreasing[x] + 1)
return result if result >= 3 else 0
|
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
|
class Solution:
def longestMountain(self, A):
up, down = [0] * len(A), [0] * len(A)
for i in range(1, len(A)):
if A[i] > A[i - 1]: up[i] = up[i - 1] + 1
for i in range(len(A) - 1)[::-1]:
if A[i] > A[i + 1]: down[i] = down[i + 1] + 1
print(down)
print(up)
return max([u + d + 1 for u, d in zip(up, down) if u and d] or [0])
|
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
|
class Solution:
def longestMountain(self, A: List[int]) -> int:
if len(A) < 3:
return 0
longestMountain = 0
for i in range(1, len(A) - 1):
# Index i denotes a 'peak' in the mountain.
if A[i - 1] < A[i] > A[i + 1]:
left = right = i
# Traverse left and down the mountain from i until there is no longer a downwards slope.
while left > 0 and A[left - 1] < A[left]:
left -= 1
# Traverse right and down the mountain from i until there is no longer a downwards slope.
while right + 1 < len(A) and A[right + 1] < A[right]:
right += 1
# The length of the mountain will be the distance from left and right (+ 1 to factor in the peak).
mountainLength = right - left + 1
longestMountain = max(longestMountain, mountainLength)
return longestMountain
|
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
|
class Solution:
def longestMountain(self, a: List[int]) -> int:
ml = 0
i = 0
while(i<len(a)):
c = 0
if i+1<len(a) and a[i+1]>a[i]:
c = 1
while(i+1<len(a) and a[i+1]>a[i]):
c = c + 1
i = i + 1
while(i+1<len(a) and a[i+1]<a[i]):
c = c + 1
ml = max(c,ml)
i = i + 1
else:
i = i + 1
return ml
|
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
|
class Solution:
def longestMountain(self, A: List[int]) -> int:
idx = 0
big = 0
while idx+1 < len(A):
long = 1
if A[idx+1] > A[idx]:
while idx+1 < len(A) and A[idx+1] > A[idx]:
idx += 1
long += 1
else:
idx += 1
continue
if idx+1 < len(A) and A[idx+1] < A[idx]:
while idx+1 < len(A) and A[idx+1] < A[idx]:
idx += 1
long += 1
else:
idx += 1
continue
big = max(long, big)
return big if big >= 3 else 0
|
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
|
class Solution:
def longestMountain(self, A):
res = up = down = 0
for i in range(1, len(A)):
if down and A[i - 1] < A[i] or A[i - 1] == A[i]: up = down = 0
up += A[i - 1] < A[i]
down += A[i - 1] > A[i]
if up and down: res = max(res, up + down + 1)
return res
|
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
|
class Solution:
def longestMountain(self, A: List[int]) -> int:
res = up = down = 0
for i in range(1, len(A)):
if down and A[i - 1] < A[i] or A[i - 1] == A[i]:
up = down = 0
if A[i - 1] < A[i]:
up += 1
else:
down += 1
if up and down:
res = max(res, up + down + 1)
return res
|
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
|
class Solution:
def longestMountain(self, A: List[int]) -> int:
n=len(A)
left_inc=[0]*n
for i in range(1,n):
if A[i]>A[i-1]:
left_inc[i]=1+left_inc[i-1]
print(left_inc)
right_inc=[0]*n
for i in range(n-2,-1,-1):
if A[i]>A[i+1]:
right_inc[i]=1+right_inc[i+1]
print(right_inc)
res=0
for i in range(n):
if left_inc[i]!=0 and right_inc[i]!=0:
res=max(res,left_inc[i]+right_inc[i]+1)
return res if res>=3 else 0
|
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
|
class Solution:
def longestMountain(self, A: List[int]) -> int:
# edge case
if len(A)==0: return 0
n = len(A)
peak = None
maxMountainLen = 0
i = 1
while (i+1) <n:
if A[i-1]<A[i] and A[i]>A[i+1]:
# already obtained the peak
left = right = i
while (left-1)>=0 and A[left-1] < A[left]:
left -= 1
while (right+1) <n and A[right+1] < A[right]:
right += 1
# max length of mountain
maxMountainLen = max(maxMountainLen, right-left+1)
i=right+1
else:
i+=1
return maxMountainLen
|
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
|
class Solution:
def longestMountain(self, A: List[int]) -> int:
i = 0
answer = 0
while i < len(A) - 1:
j = i + 1
visited_top = False
while j < len(A):
print(i, j)
if A[j] > A[j-1]:
if visited_top:
break
if A[j] < A[j-1]:
if not visited_top:
if j - i == 1:
break
visited_top = True
if A[j] == A[j-1]:
break
j += 1
if visited_top and j - i > 2:
answer = max(answer, j - i)
i = j
if visited_top:
i -= 1
return answer
|
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
|
class Solution:
def longestMountain(self, A: List[int]) -> int:
import copy
if not A:
return 0
dp = []
B = copy.deepcopy(A)
B.insert(0, A[0])
B.append(A[-1])
for i in range(1,len(B) - 1):
if (B[i-1] < B[i] and B[i+1] < B[i]):
dp.append(i-1)
ret = []
A.append(A[-1])
for top in dp:
left = top
while A[left - 1] < A[left] and left > 0:
left -= 1
right = top
while A[right + 1] < A[right]:
right +=1
print(right, left)
ret.append(right -left + 1)
print(dp, ret)
return max(ret) if ret else 0
|
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
|
class Solution:
def longestMountain(self, A: List[int]) -> int:
if not A or len(A)==1: return 0
m=len(A)
up,down=[0 for i in range(m)],[0 for i in range(m)]
up[0], down[-1]=0,0
for i in range(1,m):
j=m-1-i
if A[i]>A[i-1]:
up[i]=up[i-1]+1
else:up[i]=0
if A[j]>A[j+1]:
down[j]=down[j+1]+1
else: down[j]=0
ans=0
for i in range(m):
if up[i] and down[i]: ## need peak
ans=max(ans,up[i]+down[i]+1)
return ans
|
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
|
class Solution:
def longestMountain(self, A: List[int]) -> int:
ans = 0
temp = 0
trend = False
if len(A)<3: return 0
good = False
for i in range(1,len(A)):
diff = A[i]-A[i-1]
if diff>0:
if not trend:
good = True
trend = True
temp = 2
else:
temp=max(temp+1,2)
elif diff<0:
if trend:
trend = False
temp = max(temp+1,2)
ans = max(ans,temp)
else:
temp=max(temp+1,2)
if good: ans = max(ans,temp)
else:
temp = 0
trend = False
good = False
print(A[i], temp,trend, ans)
# ans = max(ans,temp)
return ans
|
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
|
class Solution:
def longestMountain(self, A: List[int]) -> int:
if len(A) < 3: return 0
up, down, Max = [1] * len(A), [1] * len(A), 0
for i in range(1, len(A)):
if A[i] > A[i - 1]: up[i] = up[i - 1] + 1
for i in range(len(A) - 2, -1, -1):
if A[i] > A[i + 1]: down[i] = down[i + 1] + 1
# print(up)
# print(down)
for i in range(1, len(A) - 1):
if A[i - 1] < A[i] > A[i + 1]:
Max = max(Max, up[i] + down[i] - 1)
return Max
|
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
|
class Solution:
def longestMountain(self, A: List[int]) -> int:
# https://leetcode.com/problems/longest-mountain-in-array/discuss/135593/C%2B%2BJavaPython-1-pass-and-O(1)-space
res = up = down = 0
for i in range(1, len(A)):
if down and A[i - 1] < A[i] or A[i - 1] == A[i]: up = down = 0
up += A[i - 1] < A[i]
down += A[i - 1] > A[i]
if up and down: res = max(res, up + down + 1)
return res
|
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
|
class Solution:
def longestMountain(self, A: List[int]) -> int:
N = len(A)
up = [1]*N
for i in range(1, N):
if A[i]>A[i-1]: up[i]+=up[i-1]
down = [1]*N
for i in range(N-2,-1, -1):
if A[i]>A[i+1]: down[i]+=down[i+1]
# print(up, down)
return max([u+d-1 for u, d in zip(up, down) if u>1 and d>1 and u+d-1>=3] or [0])
|
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
|
class Solution:
def longestMountain(self, A: List[int]) -> int:
res = up = down = 0
for i in range(1, len(A)):
if down and A[i-1] < A[i] or A[i-1] == A[i]: # to check if we found down and the next is up
up = down = 0 # reset for next down and make sure we are counting right up's
up += A[i-1] < A[i]
down += A[i-1] > A[i]
if up and down:
res = max(res, up+down+1)
return res
|
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
|
class Solution:
def longestMountain(self, A: List[int]) -> int:
if not A: return 0
# None -> Haven't started a mountain, True -> rising up, False -> Falling down
rising = None
curr = 0
best = 0
prev = None
for i,x in enumerate(A):
print((i,':', x, 'curr', curr))
if prev is None:
prev = x
curr = best = 1
continue
if rising is None and x < prev:
prev = x
continue
if rising is None and x > prev:
rising = True
prev = x
curr = 2
continue
# Continue rising
if rising and x > prev:
curr += 1
# Continue falling
elif not rising and x < prev:
curr += 1
# Failure regardless of rising/not rising
elif x == prev:
rising = None
best = max(best, curr)
# Was rising, gonna fall now
elif rising and x < prev:
rising = False
curr += 1
# Was falling, gonna start a new mountain
elif not rising and x > prev:
best = max(best, curr)
rising = True
curr = 2 # x and the previous
prev = x
# Check if
if rising is not None and not rising:
best = max(best, curr)
return 0 if best < 3 else best
|
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
|
class Solution:
def longestMountain(self, A: List[int]) -> int:
N = len(A)
start = 0
ans = 0
while start < N:
end = start
if end + 1 < N and A[end] < A[end+1]:
while end + 1 < N and A[end] < A[end+1]:
end +=1
if end + 1 < N and A[end] > A[end+1]:
while end + 1 < N and A[end] > A[end+1]:
end +=1
ans = max(ans, end-start+1)
start = max(end, start+1)
return ans
|
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
|
class Solution:
def longestMountain(self, A: List[int]) -> int:
if len(A) == 0:
return 0
increasing = False
count = -float('inf')
last = A[0]
max_len = 0
for i in range(1,len(A)):
if A[i] > last and increasing:
count += 1
elif A[i] > last and not increasing:
count = 2
increasing = True
elif A[i] < last and increasing:
count += 1
increasing = False
max_len = max(max_len, count)
elif A[i] < last and not increasing:
count += 1
max_len = max(max_len, count)
else:
if not increasing:
max_len = max(max_len, count)
count = -float('inf')
increasing = False
last = A[i]
if max_len < 3:
return 0
return max_len
|
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
|
class Solution:
def longestMountain(self, A):
res = up = down = 0
for i in range(1, len(A)):
if down and A[i - 1] < A[i] or A[i - 1] == A[i]: up = down = 0
up += A[i - 1] < A[i]
down += A[i - 1] > A[i]
if up and down: res = max(res, up + down + 1)
return res
|
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
|
class Solution:
def longestMountain(self, A: List[int]) -> int:
if not A or len(A) < 3:
return 0
left = right = mid = max_moun = 0
while right < len(A):
prev = mid
while right + 1 < len(A) and A[right + 1] > A[right]:
right += 1
mid += 1
if prev != mid:
while right + 1 < len(A) and A[right + 1] < A[right]:
right += 1
if mid != 0 and mid != len(A) - 1:
max_moun = max(max_moun, right - left + 1)
right = mid + 1
left = right
mid = right
if max_moun < 3:
return 0
return max_moun
|
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
|
class Solution:
def longestMountain(self, A: List[int]) -> int:
left = right = 0
max_length = 0
while left < len(A):
prev = A[left]
climbing = False
descending = False
right = left + 1
while right < len(A):
current = A[right]
if prev < current and not descending:
climbing = True
elif prev > current and (climbing or descending):
climbing = False
descending = True
else:
right -= 1
break
right += 1
prev = current
if right == len(A):
right -= 1
curr_length = right - left + 1
if curr_length > 2 and descending:
max_length = max(max_length, curr_length)
left = max(left + 1, right)
return max_length
|
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
|
class Solution:
def mountain_search(self,start,A):
valid_mountain = True
i = start
while (i < len(A)-1 and A[i] < A[i+1]):
i+=1
if (i < len(A)-1 and A[i] != A[i+1]):
while (i < len(A)-1 and A[i] > A[i+1]):
i+=1
else:
valid_mountain = False
return valid_mountain, i
def longestMountain(self, A: List[int]) -> int:
# Idea: go through every element in array and try to build largest mountain
max_mountain = 0
i = 0
if not A: return 0
A.append(A[-1]+1)
while i < len(A)-3:
if A[i] < A[i+1]:
valid, new_i = self.mountain_search(i, A)
if valid:
max_mountain = max(max_mountain, new_i-i+1)
i = new_i
else:
i+=1
return max_mountain
|
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
|
class Solution:
def longestMountain(self, A: List[int]) -> int:
res = 0
for i in range(1,len(A) - 1):
if A[i + 1] < A[i] > A[i - 1]:
l = r = i
while l and A[l] > A[l - 1]:
l -= 1
while r + 1 < len(A) and A[r] > A[r + 1]:
r += 1
if r - l + 1 > res:
res = r - l + 1
return res
|
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
|
class Solution:
def longestMountain(self, A: List[int]) -> int:
is_peak = False
index = 1
longest = 0
while index < len(A) - 1:
if A[index] > A[index-1] and A[index] > A[index+1]:
is_peak = True
if not is_peak:
index += 1
continue
left = index-1
while left-1 >= 0 and A[left] > A[left-1]:
left -= 1
right = index+1
while right+1 < len(A) and A[right] > A[right+1]:
right += 1
longest = max(longest, right-left+1)
index = right
is_peak = False
return longest
|
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
|
class Solution:
def longestMountain(self, A: List[int]) -> int:
up = down = ans = 0
for i in range(1, len(A)):
if A[i-1]==A[i]:
up = down = 0
elif A[i-1]<A[i]:
if down or up==0:
up = 2
down = 0
else:
up += 1
else:
down += 1
if up and down:
ans = max(ans, up+down)
return ans
'''
up = down = ans = 0
for i in range(1, len(A)):
if A[i-1]>A[i] and up:
down += 1
if A[i-1]==A[i] or A[i-1]<A[i] and down or i==len(A)-1:
if up and down:
ans = max(ans, up+down)
up = down = 0
if A[i-1]<A[i]:
up = 2 if not up else up+1
return ans
'''
'''
l = ans = 0
phase = 0 #0:ascend, 1: descend
for r in range(1, len(A)):
if phase==0:
if A[r-1]==A[r]:
l = r
elif A[r-1]>A[r]:
if l+1<r:
phase = 1
else:
l = r
if phase==1:
if A[r-1]<=A[r] or r==len(A)-1:
ans = max(ans, r-l)
if r==len(A)-1 and A[r-1]>A[r] and r-l==ans:
ans += 1
l = r if A[r-1]==A[r] else r-1
phase = 0
return ans
'''
|
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
|
class Solution:
def longestMountain(self, A: List[int]) -> int:
res = cur = 1
desc = False
for i in range(1, len(A)):
if A[i-1] == A[i]:
if desc: res = max(res, cur)
desc = False
cur = 1
elif A[i-1] < A[i]:
if not desc: cur += 1
else:
res = max(res, cur)
cur = 2
desc = False
else:
if desc: cur += 1
elif cur > 1:
desc = True
cur += 1
else:
cur = 1
desc = False
if desc: res = max(res, cur)
return 0 if res < 3 and not desc else res
|
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
|
class Solution:
def longestMountain(self, A: List[int]) -> int:
res = 0
i = 0
while i < len(A):
j = i
while j + 1 < len(A) and A[j] < A[j+1]:
j += 1
mid = j
while j + 1 < len(A) and A[j] > A[j+1]:
j += 1
if i < mid < j:
res = max(res, j-i+1)
if i == j:
i +=1
else:
i = j
return res
|
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
|
'''
mountain = relative maximum
- find decr and incr after mountain
[2,1,4,7,3,2,5]
[2,3,2]
while j < len
use flag to incr and decr
while next and next incr
j+=1
if not incr:
incr and cont
while next and next decr
j+=1
if not decr:
incr and cont
if len 3
check/override max
'''
class Solution:
def longestMountain(self, A: List[int]) -> int:
long_mont = 0
i, j = 0, 0
while j < len(A):
incr = False
while j!=len(A)-1 and A[j] < A[j+1]:
incr = True
j+=1
if not incr:
j+=1
i=j
continue
decr = False
while j!=len(A)-1 and A[j] > A[j+1]:
decr = True
j+=1
if not decr:
j+=1
i=j
continue
curr_len = j-i+1
if curr_len >= 3:
long_mont = max(long_mont, curr_len)
i = j
return long_mont
|
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
|
class Solution(object):
def longestMountain(self, A):
N = len(A)
ans = base = 0
while base < N:
end = base
if end + 1 < N and A[end] < A[end + 1]: #if base is a left-boundary
#set end to the peak of this potential mountain
while end+1 < N and A[end] < A[end+1]:
end += 1
if end + 1 < N and A[end] > A[end + 1]: #if end is really a peak..
#set 'end' to right-boundary of mountain
while end+1 < N and A[end] > A[end+1]:
end += 1
#record candidate answer
ans = max(ans, end - base + 1)
base = max(end, base + 1)
return ans
|
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
|
class Solution:
def longestMountain(self, A: List[int]) -> int:
# Write your code here.
longest, i = 0, 1
while i < len(A) - 1:
is_peak = A[i-1] < A[i] and A[i] > A[i+1]
#Check if i is peak
if is_peak:
left = i-2
#Move left pointer left while in bounds and greater
while left >= 0 and A[left] < A[left + 1]:
left -= 1
right = i + 2
#Move right pointer right while in bounds and greater
while right < len(A) and A[right] < A[right - 1]:
right += 1
#Current peak
longest = max(longest, right - left - 1)
#Increment i
i = right
#If i is not peak, increment and continue.
else:
i += 1
continue
return longest
|
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
|
class Solution:
def longestMountain(self, A: List[int]) -> int:
if len(A)<3:
return 0
a=A
start =0
end = 0
maxlen=0
n=len(a)
while(start<n-1 and end<n):
end = start
if a[start]<a[start+1]:
while end<n-1 and a[end]<a[end+1]:
end+=1
if end<n-1 and a[end]>a[end+1]:
while(end<n-1 and a[end]>a[end+1]):
end +=1
maxlen = max(maxlen,end-start+1)
start = max(start+1,end)
return maxlen
|
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
Above is a 7 x 3 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
Example 1:
Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right
Example 2:
Input: m = 7, n = 3
Output: 28
|
class Solution:
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
def f(n):
ret = 1
for i in range(1, n+1):
ret *= i
return ret
return f(m+n-2)//(f(m-1)*f(n-1))
|
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
Above is a 7 x 3 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
Example 1:
Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right
Example 2:
Input: m = 7, n = 3
Output: 28
|
class Solution:
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
sol = [[0 for j in range(n)] for i in range(m)]
sol[0][0] = 1
for i in range(0, m ):
for j in range(0, n ):
if i == 0 or j == 0: sol[i][j] = 1
else: sol[i][j] = sol[i-1][j] + sol[i][j-1]
return sol[-1][-1]
|
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
Above is a 7 x 3 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
Example 1:
Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right
Example 2:
Input: m = 7, n = 3
Output: 28
|
class Solution:
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
counts = {}
counts[(1, 1)] = 1
for r in range(2, m+ 1):
counts[(r, 1)] = 1
for c in range(2, n + 1):
counts[(1, c)] = 1
for i in range(2, m +1):
for j in range(2, n + 1):
counts[(i, j)] = counts[(i - 1, j)] + counts[(i, j -1)]
return counts[(m, n)]
def temp(self, m, n):
cache = {}
def go(m, n):
if m == 1 and n == 1:
return 1
count = 0
if m > 1:
if (m -1, n) not in cache:
cache[(m-1, n)] = go(m-1, n)
count += cache[(m-1, n)]
if n > 1:
if (m, n - 1) not in cache:
cache[(m, n-1)] = go(m, n-1)
count += cache[(m, n -1)]
return count
return go(m, n)
|
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
Above is a 7 x 3 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
Example 1:
Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right
Example 2:
Input: m = 7, n = 3
Output: 28
|
class Solution:
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
a = m - 1
b = n - 1
ret = 1
for i in range(b):
ret = ret * (a+b-i) / (b-i)
return round(ret)
|
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
Above is a 7 x 3 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
Example 1:
Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right
Example 2:
Input: m = 7, n = 3
Output: 28
|
class Solution:
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
num_paths = [[0 for _ in range(n)] for _ in range(m)]
for i in range(m):
for j in range(n):
above = num_paths[i-1][j] if i > 0 else 0
left = num_paths[i][j-1] if j > 0 else 0
num_paths[i][j] = above + left
if i==0 and j==0:
num_paths[0][0] = 1
return num_paths[m-1][n-1]
|
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
Above is a 7 x 3 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
Example 1:
Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right
Example 2:
Input: m = 7, n = 3
Output: 28
|
class Solution:
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
aux = [[1 for x in range(n)] for x in range(m)]
for i in range(1, m):
for j in range(1, n):
aux[i][j] = aux[i][j-1]+aux[i-1][j]
return aux[-1][-1]
|
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
Above is a 7 x 3 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
Example 1:
Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right
Example 2:
Input: m = 7, n = 3
Output: 28
|
class Solution:
def __init__(self):
self.dp = [[0 for _ in range(101)] for _ in range(101)]
def go(self, x, y, m, n):
if self.dp[x][y] == 0:
if x == m or y == n:
self.dp[x][y] = 0
elif x == m - 1 and y == n - 1:
self.dp[x][y] = 1
elif x == m - 1 and y == n-1:
self.dp[x][y] = 1
else:
self.dp[x][y] = self.go(x+1, y, m, n) + self.go(x, y+1, m, n)
return self.dp[x][y]
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
return self.go(0, 0, m, n)
|
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
Above is a 7 x 3 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
Example 1:
Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right
Example 2:
Input: m = 7, n = 3
Output: 28
|
class Solution:
import math
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
if m==1 or n==1:
return 1
r,c = m-1, n-1
return int(math.factorial(r+c)/(math.factorial(r)*math.factorial(c)))
|
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
Above is a 7 x 3 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
Example 1:
Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right
Example 2:
Input: m = 7, n = 3
Output: 28
|
class Solution:
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
if 0 in (m,n):return 0
results = [[1] * n]*m
for i in range(1, m):
for j in range(1, n):
results[i][j] = results[i-1][j] + results[i][j-1]
return results[m-1][n-1]
|
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
Above is a 7 x 3 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
Example 1:
Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right
Example 2:
Input: m = 7, n = 3
Output: 28
|
class Solution:
def uniquePaths(self, m, n, memo = None):
"""
:type m: int
:type n: int
:rtype: int
"""
if m == 1 and n == 1:
return 1
if m < 1 or n < 1:
return 0
if not memo:
memo = [[0 for i in range(n+1)] for j in range(m+1)]
if memo[m][n]:
return memo[m][n]
else:
memo[m][n] = self.uniquePaths(m-1, n, memo) + self.uniquePaths(m, n-1, memo)
return memo[m][n]
|
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
Above is a 7 x 3 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
Example 1:
Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right
Example 2:
Input: m = 7, n = 3
Output: 28
|
class Solution:
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
M = [[1 for _ in range(n)] for _ in range(2)]
for i in range(m-1, -1, -1):
for j in range(n-1, -1, -1):
if i == m-1 or j == n-1: continue
else: M[i%2][j] = M[(i+1)%2][j] + M[i%2][j+1]
return M[0][0]
|
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
Above is a 7 x 3 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
Example 1:
Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right
Example 2:
Input: m = 7, n = 3
Output: 28
|
class Solution:
def paths(self,m,n,a,b,memo):
if m>a or n>b:
return 0
if m==a and n==b:
return 1
if str(m)+" "+str(n) not in memo:
memo[str(m)+" "+str(n)] = self.paths(m+1,n,a,b,memo) + self.paths(m,n+1,a,b,memo)
return memo[str(m)+" "+str(n)]
def uniquePaths(self, m, n):
memo = dict()
return(self.paths(0,0,m-1,n-1,memo))
|
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
Above is a 7 x 3 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
Example 1:
Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right
Example 2:
Input: m = 7, n = 3
Output: 28
|
class Solution:
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
matrix = [[0 for j in range(n)] for i in range(m)]
matrix[0][0] = 1
for i in range(m):
for j in range(n):
if i == 0 and j == 0:
continue
elif i == 0:
matrix[i][j] = matrix[i][j-1]
elif j == 0:
matrix[i][j] = matrix[i-1][j]
else:
matrix[i][j] = matrix[i][j-1]+matrix[i-1][j]
return matrix[m-1][n-1]
|
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
Above is a 7 x 3 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
Example 1:
Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right
Example 2:
Input: m = 7, n = 3
Output: 28
|
class Solution:
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
all=m-1+n-1
x=1
y=1
for i in range(m-1):
x=x*(all-i)
y=y*(i+1)
return x//y
|
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Your algorithm's runtime complexity must be in the order of O(log n).
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
|
class Solution:
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
# left = 0
# right = len(nums) - 1
# while left <= right:
# mid = int((left + right)/2)
# if nums[mid] == target:
# return mid
# elif (nums[right] < target) or (nums[mid] > target and nums[right] > target):
# right = mid - 1
# else:
# left = mid + 1
# return -1
left = 0
right = len(nums) - 1
while left <= right:
mid = int((left + right)/2)
if nums[mid] == target:
return mid
if (nums[left] < nums[mid]):
if (target < nums[left]) or (target > nums[mid]):
left = mid + 1
else:
right = mid - 1
elif (nums[left] > nums[mid]):
if (target < nums[mid]) or (target >= nums[left]):
right = mid - 1
else:
left = mid + 1
else:
if nums[right] == target:
return right
else:
return -1
return -1
|
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Your algorithm's runtime complexity must be in the order of O(log n).
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
|
class Solution:
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
l, r = 0, len(nums)-1
while l <= r:
mid = (l+r)//2
if nums[mid] == target:
return mid
elif nums[mid] >= nums[l]:
if nums[l] <= target < nums[mid]:
r = mid-1
else:
l = mid+1
else:
if nums[mid] < target <= nums[r]:
l = mid+1
else:
r = mid-1
return -1
|
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Your algorithm's runtime complexity must be in the order of O(log n).
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
|
class Solution:
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
length = len(nums)
if length <= 0:
return -1
pivot = self.find_pivot(0, length-1, nums)
print(pivot)
search_index_A = self.binary_search(0, max(pivot-1, 0), nums, target)
search_index_B = self.binary_search(pivot, length-1, nums, target)
if search_index_A >= 0:
return search_index_A
elif search_index_B >= 0:
return search_index_B
else:
return -1
def find_pivot(self, left_ind, right_ind, nums):
mid = left_ind + (right_ind - left_ind)//2
if left_ind == right_ind:
return left_ind
elif nums[mid] < nums[mid-1]:
return mid
elif nums[right_ind] < nums[mid]:
return self.find_pivot(mid+1, right_ind, nums)
else:
return self.find_pivot(left_ind, max(0,mid-1), nums)
def binary_search(self, left_ind, right_ind, nums, target):
mid = left_ind + (right_ind - left_ind)//2
if nums[mid] == target:
return mid
elif left_ind == right_ind:
return -1
elif nums[mid] < target:
return self.binary_search(mid+1, right_ind, nums, target)
else:
return self.binary_search(left_ind, max(left_ind,mid-1), nums, target)
|
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Your algorithm's runtime complexity must be in the order of O(log n).
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
|
class Solution:
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
left, right = 0, len(nums)-1
while left <= right:
mid = (left+right) // 2
if nums[mid] == target:
return mid
elif nums[mid] >= nums[left]:
if nums[left] <= target < nums[mid]:
right = mid-1
else:
left = mid+1
else:
if nums[mid] < target <= nums[right]:
left = mid+1
else:
right = mid-1
return -1
|
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Your algorithm's runtime complexity must be in the order of O(log n).
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
|
class Solution:
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
# if target in nums:
# return nums.index(target)
# else:
# return -1
low, high = 0, len(nums)-1
while low < high:
mid = (low+high)//2
if nums[mid] > nums[high]:
low = mid+1
else:
high = mid
start = low
low, high = 0, len(nums)-1
while low <= high:
mid = (low+high)//2
realMid = (mid+start) % (len(nums))
if nums[realMid] == target:
return realMid
if target > nums[realMid]:
low = mid+1
else:
high = mid-1
return -1
|
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Your algorithm's runtime complexity must be in the order of O(log n).
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
|
class Solution:
def search_interval(self, start, end, nums, target):
if start == end:
if nums[start] == target:
return start
else:
return -1
size = end - start
half = size // 2
new_start_1 = start
new_end_1 = start + half
new_start_2 = start + half + 1
new_end_2 = end
# check first interval
first_half_sorted = False
first_half_contains = False
second_half_sorted = False
second_half_contains = False
if nums[new_end_1] >= nums[new_start_1]:
first_half_sorted = True
if (target >= nums[new_start_1]) and (target <= nums[new_end_1]):
first_half_contains = True
if nums[new_end_2] >= nums[new_start_2]:
second_half_sorted = True
if (target >= nums[new_start_2]) and (target <= nums[new_end_2]):
second_half_contains = True
if first_half_contains:
return self.search_interval(new_start_1, new_end_1, nums, target)
elif second_half_contains:
return self.search_interval(new_start_2, new_end_2, nums, target)
elif first_half_sorted:
return self.search_interval(new_start_2, new_end_2, nums, target)
elif second_half_sorted:
return self.search_interval(new_start_1, new_end_1, nums, target)
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if len(nums) == 0:
return -1
return self.search_interval(0, len(nums) - 1, nums, target)
|
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Your algorithm's runtime complexity must be in the order of O(log n).
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
|
class Solution:
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
length = len(nums)
if length <= 0:
return -1
pivot = self.find_pivot(0, length-1, nums)
print(pivot)
search_index_A = self.binary_search(0, max(pivot-1, 0), nums, target)
search_index_B = self.binary_search(pivot, length-1, nums, target)
if search_index_A >= 0:
return search_index_A
elif search_index_B >= 0:
return search_index_B
else:
return -1
def find_pivot(self, left_ind, right_ind, nums):
mid = left_ind + (right_ind - left_ind)//2
if left_ind == right_ind:
return left_ind
elif nums[mid] < nums[mid-1]:
return mid
elif nums[right_ind] < nums[mid]:
return self.find_pivot(mid+1, right_ind, nums)
else:
return self.find_pivot(left_ind, max(0,mid-1), nums)
def binary_search(self, left_ind, right_ind, nums, target):
mid = left_ind + (right_ind - left_ind)//2
print(nums)
print(mid)
if nums[mid] == target:
return mid
elif left_ind == right_ind:
return -1
elif nums[mid] < target:
return self.binary_search(mid+1, right_ind, nums, target)
else:
return self.binary_search(left_ind, max(left_ind,mid-1), nums, target)
# [5,1,3]
# [0]
# find_pivot(0,2,[5,1,3])
# left = 0
# right = 2
# mid = 0 + 2//2 = 1
# nums[mid] < nums[mid-1]
# pivot = 1
# binary_search(0, max(pivot-1,0), ...)
# left = 0, right = 0
# search_index_A = -1
# binary_search(pivot, length-1, ...)
# left = 1, right = 2
# mid = 1 + (2-1)//2 = 1
# binary_search(1, max(0,0), ...)
# search_index_B = -1
|
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Your algorithm's runtime complexity must be in the order of O(log n).
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
|
class Solution:
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
idx = -1
for i in range(1,len(nums)):
if nums[i] < nums[i-1]:
idx = i
break
if idx == -1:
return self.bin_search(nums, 0, len(nums), target)
else:
if target < nums[0] or target < nums[-1]:
return self.bin_search(nums, idx, len(nums), target)
elif target > nums[-1] or target > nums[0]:
return self.bin_search(nums, 0, idx, target)
else:
assert(False)
def bin_search(self, nums, i1, i2, target):
while i1 < i2:
mi = (i1 + i2) // 2
if nums[mi] == target: return mi
if nums[mi] > target: i2 = mi
else: i1 = mi + 1
return -1
|
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Your algorithm's runtime complexity must be in the order of O(log n).
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
|
class Solution:
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
for i in range(0,len(nums)):
if nums[i] == target:
return i
return -1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.