New interview questions
cibic89 opened this issue · 0 comments
cibic89 commented
Fibonacci
# Iterative solution
def fibonacci(n):
# special case
if n == 1:
return [0]
# initialize the array
arr = [0, 1]
# and populate it, remember to skip the 2 values that are already
present
for i in range(2, n):
arr.append(arr[-1]+arr[-2])
return arr
# Recursive solution
def fibonacci(n):
# handle special cases
print(n)
if n < 2:
return [0]
if n < 3:
return [0, 1]
# normal case as n decreases from original value to 2
arr = fibonacci(n-1)
arr.append(arr[n-2] + arr[n-3])
return arr
Find the sequence Sum
def getSequenceSum(i, j, k, x):
cnt_inc = (j - i) // x + 1
cnt_dec = (j - k) // x + 1
inc_sum = (cnt_inc * (i + j)) // 2
dec_sum = (cnt_dec * (j + k)) // 2
tot_sum = inc_sum + dec_sum - j
return tot_sum
Maximizing Profit from Stocks
def maximumProfit(prices):
m = prices.pop()
maxsum = 0
arrsum = 0
for p in reversed(prices):
m = max(m, p)
maxsum+=m
arrsum+=p
return maxsum-arrsum