Arrays
Arrays
Q3 Kadane’s Algorithm
class Solution:
def maxSubArraySum(self,arr,N):
curr_sum = 0
max_sum = arr[0]
for i in range(N):
curr_sum += arr[i]
max_sum = max(max_sum, curr_sum)
if curr_sum < 0: curr_sum = 0
return max_sum
if j < m:
j = 0
while j + gap < m:
if arr2[j] > arr2[j + gap]:
arr2[j], arr2[j + gap] = \
arr2[j + gap], arr2[j]
j += 1
if gap <= 1:
gap = 0
else:
gap = ceil(gap/2)
for i in range(n):
arr[i] = arr[i]//me
Q7 Number of pairs
from bisect import bisect_right
class Solution:
def countPairs(self,a,b,M,N):
b.sort()
count_of_0 = bisect_right(b, 0)
count_of_1 = bisect_right(b, 1) - count_of_0
count_of_2 = bisect_right(b, 2) - bisect_right(b,1)
count = 0
for x in a:
if x == 0: continue
elif x == 1:
count += count_of_0
elif x == 2:
count += N - bisect_right(b, 4) + \
count_of_0 + count_of_1
elif x == 3:
count += N - bisect_right(b, 3) + \
count_of_2 + count_of_0 + count_of_1
else:
count += N - bisect_right(b, x) + \
count_of_0 + count_of_1
return count