text stringlengths 17 2.11k | code stringlengths 82 3.44k |
|---|---|
Find minimum number K such that sum of array after multiplication by K exceed S | Python3 implementation of the approach ; Function to return the minimum value of k that satisfies the given condition ; store sum of array elements ; Calculate the sum after ; return minimum possible K ; Driver code | import math
def find_minimum_k(a, n, S):
"""
Find minimum number K such that sum of array after multiplication by K exceed S
"""
sum = 0
for i in range(0, n):
sum += a[i]
return math.ceil(((S + 1) * 1.0) / (sum * 1.0))
a = [10, 7, 8, 10, 12, 19]
n = len(a)
s = 200
print(find_minimum_... |
Find the largest number smaller than integer N with maximum number of set bits | Function to return the largest number less than N ; Iterate through all possible values ; Multiply the number by 2 i times ; Return the final result ; Driver code | def largest_num(n):
"""
Find the largest number smaller than integer N with maximum number of set bits
"""
num = 0
for i in range(32):
x = (1 << i)
if ((x - 1) <= n):
num = (1 << i) - 1
else:
break
return num
if __name__ == "__main__":
N = 34... |
Find the String having each substring with exactly K distinct characters | Function to find the required output string ; Each element at index i is modulus of K ; Driver code ; initialise integers N and K | def find_string(N, K):
"""
Find the String having each substring with exactly K distinct characters
"""
for i in range(N):
print(chr(ord('A') + i % K), end="")
if __name__ == "__main__":
N = 10
K = 3
find_string(N, K)
|
Find total no of collisions taking place between the balls in which initial direction of each ball is given | Function to count no of collision ; Length of the string ; Driver code | def count(s):
"""
Find total no of collisions taking place between the balls in which initial direction of each ball is given
"""
cnt, ans = 0, 0
N = len(s)
for i in range(N):
if (s[i] == 'R'):
cnt += 1
if (s[i] == 'L'):
ans += cnt
return ans
s = "RR... |
Maximum number on 7 | Function to find the maximum number that can be displayed using the N segments ; Condition to check base case ; Condition to check if the number is even ; Condition to check if the number is odd ; Driver Code | def segments(n):
"""
Maximum number on 7
"""
if (n == 1 or n == 0):
return
if (n % 2 == 0):
print("1", end="")
segments(n - 2)
elif (n % 2 == 1):
print("7", end="")
segments(n - 3)
if __name__ == "__main__":
n = 11
segments(n)
|
Minimum number of subsequences required to convert one string to another using Greedy Algorithm | Function to find the minimum number of subsequences required to convert one to another S2 == A and S1 == B ; At least 1 subsequence is required Even in best case , when A is same as B ; size of B ; size of A ; Create an 2D... | def find_minimum_subsequences(A, B):
"""
Minimum number of subsequences required to convert one string to another using Greedy Algorithm
"""
numberOfSubsequences = 1
sizeOfB = len(B)
sizeOfA = len(A)
inf = 1000000
next = [[inf for i in range(sizeOfB)]for i in range(26)]
for i in rang... |
Vertical and Horizontal retrieval ( MRT ) on Tapes | Python3 program to print Horizontal filling ; It is used for checking whether tape is full or not ; It is used for calculating total retrieval time ; It is used for calculating mean retrieval time ; vector is used because n number of records can insert in one tape wi... | def horizontal_fill(records, tape, nt):
"""
Vertical and Horizontal retrieval ( MRT ) on Tapes
"""
sum = 0
Retrieval_Time = 0
current = 0
v = []
for i in range(nt):
'
v.clear()
Retrieval_Time = 0
sum = 0
print("tape", i + 1, ": [ ", end="")
sum += records[current]
while (sum <= t... |
Circular Convolution using Matrix Method | Python program to compute circular convolution of two arrays ; Function to find circular convolution ; Finding the maximum size between the two input sequence sizes ; Copying elements of x to row_vec and padding zeros if size of x < maxSize ; Copying elements of h to col_vec a... | MAX_SIZE = 10
def convolution(x, h, n, m):
"""
Circular Convolution using Matrix Method
"""
row_vec = [0] * MAX_SIZE
col_vec = [0] * MAX_SIZE
out = [0] * MAX_SIZE
circular_shift_mat = [[0 for i in range(MAX_SIZE)]for j in range(MAX_SIZE)]
if (n > m):
maxSize = n
else:
... |
Maximize the number of palindromic Strings | Python3 program for the above approach ; To check if there is any string of odd length ; If there is at least 1 string of odd length . ; If all the strings are of even length . ; Count of 0 's in all the strings ; Count of 1 's in all the strings ; If z is even and o is ev... | def max_palindrome(s, n):
"""
Maximize the number of palindromic Strings
"""
flag = 0
for i in range(n):
if (len(s[i]) % 2 != 0):
flag = 1
if (flag == 1):
return n
z = 0
o = 0
for i in range(n):
for j in range(len(s[i])):
if (s[i][j] ==... |
Minimum possible travel cost among N cities | Function to return the minimum cost to travel from the first city to the last ; To store the total cost ; Start from the first city ; If found any city with cost less than that of the previous boarded bus then change the bus ; Calculate the cost to travel from the currently... | def min_cost(cost, n):
"""
Minimum possible travel cost among N cities
"""
totalCost = 0
boardingBus = 0
for i in range(1, n):
if (cost[boardingBus] > cost[i]):
totalCost += ((i - boardingBus) * cost[boardingBus])
boardingBus = i
totalCost += ((n - boardingBus... |
Minimum cost to convert str1 to str2 with the given operations | Function to return the minimum cost to convert str1 to sr2 ; For every character of str1 ; If current character is not equal in both the strings ; If the next character is also different in both the strings then these characters can be swapped ; Change th... | def min_cost(str1, str2, n):
"""
Minimum cost to convert str1 to str2 with the given operations
"""
cost = 0
for i in range(n):
if (str1[i] != str2[i]):
if (i < n - 1 and str1[i + 1] != str2[i + 1]):
swap(str1[i], str1[i + 1])
cost += 1
... |
Partition first N natural number into two sets such that their sum is not coprime | Function to find the required sets ; Impossible case ; Sum of first n - 1 natural numbers ; Driver code | def find_set(n):
"""
Partition first N natural number into two sets such that their sum is not coprime
"""
if (n <= 2):
print("-1")
return
sum1 = (n * (n - 1)) / 2
sum2 = n
print(sum1, " ", sum2)
n = 8
find_set(n)
|
Check whether a subsequence exists with sum equal to k if arr [ i ] > 2 * arr [ i | Function to check whether sum of any set of the array element is equal to k or not ; Traverse the array from end to start ; if k is greater than arr [ i ] then subtract it from k ; If there is any subsequence whose sum is equal to k ; D... | def check_for_sequence(arr, n, k):
"""
Check whether a subsequence exists with sum equal to k if arr [ i ] > 2 * arr [ i
"""
for i in range(n - 1, -1, -1):
if (k >= arr[i]):
k -= arr[i]
if (k != 0):
return False
else:
return True
if __name__ == "__main__":
... |
Maximum possible sub | Function to return the maximum sub - array sum after at most x swaps ; To store the required answer ; For all possible intervals ; Keep current ans as zero ; To store the integers which are not part of the sub - array currently under consideration ; To store elements which are part of the sub - a... | def subarray_sum(a, n, x):
"""
Maximum possible sub
"""
ans = -10000
for i in range(n):
for j in range(i, n):
curans = 0
pq = []
pq2 = []
for k in range(n):
if (k >= i and k <= j):
curans += a[k]
pq2.append(a[k])
else:
... |
Generate an array of size K which satisfies the given conditions | Python3 implementation of the approach ; Function to generate and print the required array ; Initializing the array ; Finding r ( from above approach ) ; If r < 0 ; Finding ceiling and floor values ; Fill the array with ceiling values ; Fill the array w... | import sys
from math import floor, ceil
def generate_array(n, k):
"""
Generate an array of size K which satisfies the given conditions
"""
array = [0] * k
remaining = n - int(k * (k + 1) / 2)
if remaining < 0:
print("NO")
sys.exit()
right_most = remaining % k
high = cei... |
Maximize the given number by replacing a segment of digits with the alternate digits given | Function to return the maximized number ; Iterate till the end of the string ; Check if it is greater or not ; Replace with the alternate till smaller ; Return original s in case no change took place ; Driver Code | def get_maximum(s, a):
"""
Maximize the given number by replacing a segment of digits with the alternate digits given
"""
s = list(s)
n = len(s)
for i in range(n):
if (ord(s[i]) - ord('0') < a[ord(s[i]) - ord('0')]):
j = i
while (j < n and (ord(s[j]) - ord('0')
... |
Number of times the largest perfect square number can be subtracted from N | Python3 implementation of the approach ; Function to return the count of steps ; Variable to store the count of steps ; Iterate while N > 0 ; Get the largest perfect square and subtract it from N ; Increment steps ; Return the required count ;... | from math import sqrt
def count_steps(n):
"""
Number of times the largest perfect square number can be subtracted from N
"""
steps = 0
while (n):
largest = int(sqrt(n))
n -= (largest * largest)
steps += 1
return steps
if __name__ == "__main__":
n = 85
print(co... |
Given count of digits 1 , 2 , 3 , 4 , find the maximum sum possible | Function to find the maximum possible sum ; To store required sum ; Number of 234 's can be formed ; Sum obtained with 234 s ; Remaining 2 's ; Sum obtained with 12 s ; Return the required sum ; Driver Code | def maxsum(c1, c2, c3, c4):
"""
Given count of digits 1 , 2 , 3 , 4 , find the maximum sum possible
"""
sum = 0
two34 = min(c2, min(c3, c4))
sum = two34 * 234
c2 -= two34
sum += min(c2, c1) * 12
return sum
c1 = 5
c2 = 2
c3 = 3
c4 = 4
print(maxsum(c1, c2, c3, c4))
|
Count of pairs from 1 to a and 1 to b whose sum is divisible by N | Function to find the distinct pairs from 1 - a & 1 - b such that their sum is divisible by n . ; pairs from 1 to n * ( a / n ) and 1 to n * ( b / n ) ; pairs from 1 to n * ( a / n ) and n * ( b / n ) to b ; pairs from n * ( a / n ) to a and 1 to n * ( ... | def find_count_of_pairs(a, b, n):
"""
Count of pairs from 1 to a and 1 to b whose sum is divisible by N
"""
ans = 0
ans += n * int(a / n) * int(b / n)
ans += int(a / n) * (b % n)
ans += (a % n) * int(b / n)
ans += int(((a % n) + (b % n)) / n)
return ans
if __name__ == '__main__':
... |
Generate array with minimum sum which can be deleted in P steps | Function to find the required array ; calculating minimum possible sum ; Array ; place first P natural elements ; Fill rest of the elements with 1 ; Driver Code | def find_array(N, P):
"""
Generate array with minimum sum which can be deleted in P steps
"""
ans = (P * (P + 1)) // 2 + (N - P)
arr = [0] * (N + 1)
for i in range(1, P + 1):
arr[i] = i
for i in range(P + 1, N + 1):
arr[i] = 1
print("The Minimum Possible Sum is: ", ans)
... |
Find Intersection of all Intervals | Function to print the intersection ; First interval ; Check rest of the intervals and find the intersection ; If no intersection exists ; Else update the intersection ; Driver code | def find_intersection(intervals, N):
"""
Find Intersection of all Intervals
"""
l = intervals[0][0]
r = intervals[0][1]
for i in range(1, N):
if (intervals[i][0] > r or intervals[i][1] < l):
print(-1)
else:
l = max(l, intervals[i][0])
r = min(r... |
Maximum count of sub | Function to return the count of the required sub - strings ; Iterate over all characters ; Count with current character ; If the substring has a length k then increment count with current character ; Update max count ; Driver Code | def max_sub_strings(s, k):
"""
Maximum count of sub
"""
maxSubStr = 0
n = len(s)
for c in range(27):
ch = chr(ord('a') + c)
curr = 0
for i in range(n - k):
if (s[i] != ch):
continue
cnt = 0
while (i < n and s[i] == ch an... |
Count valid pairs in the array satisfying given conditions | Function to return total valid pairs ; Initialize count of all the elements ; frequency count of all the elements ; Add total valid pairs ; Exclude pairs made with a single element i . e . ( x , x ) ; Driver Code ; Function call to print required answer | def valid_pairs(arr):
"""
Count valid pairs in the array satisfying given conditions
"""
count = [0] * 121
for ele in arr:
count[ele] += 1
ans = 0
for eleX, countX in enumerate(count):
for eleY, countY in enumerate(count):
if eleX < eleY:
continue
... |
Distribution of candies according to ages of students | Function to check The validity of distribution ; Stroring the max age of all students + 1 ; Stroring the max candy + 1 ; creating the frequency array of the age of students ; Creating the frequency array of the packets of candies ; pointer to tell whether we have ... | def check_distribution(n, k, age, candy):
"""
Distribution of candies according to ages of students
"""
mxage = max(age) + 1
mxcandy = max(candy) + 1
fr1 = [0] * mxage
fr2 = [0] * mxcandy
for j in range(n):
fr1[age[j]] += 1
for j in range(k):
fr2[candy[j]] += 1
k ... |
Minimum number of 1 's to be replaced in a binary array | Function to find minimum number of 1 ' s ▁ to ▁ be ▁ replaced ▁ to ▁ 0' s ; return final answer ; Driver Code | def min_changes(A, n):
"""
Minimum number of 1 's to be replaced in a binary array
"""
cnt = 0
for i in range(n - 2):
if ((i - 1 >= 0) and A[i - 1] == 1 and A[i + 1] == 1 and A[i] == 0):
A[i + 1] = 0
cnt = cnt + 1
return cnt
A = [1, 1, 0, 1, 1, 0, 1, 0, 1, 0]
n ... |
Number of closing brackets needed to complete a regular bracket sequence | Function to find number of closing brackets and complete a regular bracket sequence ; Finding the length of sequence ; Counting opening brackets ; Counting closing brackets ; Checking if at any position the number of closing bracket is more then... | def complete_sequence(s):
"""
Number of closing brackets needed to complete a regular bracket sequence
"""
n = len(s)
open = 0
close = 0
for i in range(n):
if (s[i] == '('):
open += 1
else:
close += 1
if (close > open):
print("IMPOS... |
Lexicographically smallest permutation with no digits at Original Index | Function to print the smallest permutation ; when n is even ; when n is odd ; handling last 3 digit ; add EOL and print result ; Driver Code | def smallest_permute(n):
"""
Lexicographically smallest permutation with no digits at Original Index
"""
res = [""] * (n + 1)
if (n % 2 == 0):
for i in range(n):
if (i % 2 == 0):
res[i] = chr(48 + i + 2)
else:
res[i] = chr(48 + i)
e... |
Minimum array insertions required to make consecutive difference <= K | Python3 implementation of above approach ; Function to return minimum number of insertions required ; Initialize insertions to 0 ; return total insertions ; Driver Code | import math
def min_insertions(H, n, K):
"""
Minimum array insertions required to make consecutive difference <= K
"""
inser = 0
for i in range(1, n):
diff = abs(H[i] - H[i - 1])
if (diff <= K):
continue
else:
inser += math.ceil(diff / K) - 1
ret... |
Minimum number of operations required to reduce N to 1 | Function that returns the minimum number of operations to be performed to reduce the number to 1 ; To stores the total number of operations to be performed ; if n is divisible by 3 then reduce it to n / 3 ; if n modulo 3 is 1 decrement it by 1 ; if n modulo 3 is ... | def count_minimum_operations(n):
"""
Minimum number of operations required to reduce N to 1
"""
count = 0
while (n > 1):
if (n % 3 == 0):
n //= 3
elif (n % 3 == 1):
n -= 1
else:
if (n == 2):
n -= 1
else:
... |
Minimum number of operations required to reduce N to 1 | Function that returns the minimum number of operations to be performed to reduce the number to 1 ; Base cases ; Driver Code | def count_minimum_operations(n):
"""
Minimum number of operations required to reduce N to 1
"""
if (n == 2):
return 1
elif (n == 1):
return 0
if (n % 3 == 0):
return 1 + count_minimum_operations(n / 3)
elif (n % 3 == 1):
return 1 + count_minimum_operations(n -... |
Maximize the sum of array by multiplying prefix of array with | Python implementation of the approach ; To store sum ; To store ending indices of the chosen prefix arrays ; Adding the absolute value of a [ i ] ; If i == 0 then there is no index to be flipped in ( i - 1 ) position ; print the maximised sum ; print the e... | def max_sum(arr, n):
"""
Maximize the sum of array by multiplying prefix of array with
"""
s = 0
l = []
for i in range(len(a)):
s += abs(a[i])
if (a[i] >= 0):
continue
if (i == 0):
l.append(i + 1)
else:
l.append(i + 1)
... |
Find the longest common prefix between two strings after performing swaps on second string | Python program to find the longest common prefix between two strings after performing swaps on the second string ; a = len ( x ) length of x b = len ( y ) length of y ; creating frequency array of characters of y ; storing the ... | def length_lcp(x, y):
"""
Find the longest common prefix between two strings after performing swaps on second string
"""
fr = [0] * 26
for i in range(b):
fr[ord(y[i]) - 97] += 1
c = 0
for i in range(a):
if (fr[ord(x[i]) - 97] > 0):
c += 1
fr[ord(x[i]) ... |
All possible co | Function to count possible pairs ; total count of numbers in range ; printing count of pairs ; Driver code | def count_pair(L, R):
"""
All possible co
"""
x = (R - L + 1)
print(x // 2)
if __name__ == '__main__':
L, R = 1, 8
count_pair(L, R)
|
Problems not solved at the end of Nth day | Function to find problems not solved at the end of Nth day ; Driver Code | def problems_left(K, P, N):
"""
Problems not solved at the end of Nth day
"""
if (K <= P):
return 0
else:
return ((K - P) * N)
K, P, N = 4, 1, 10
print(problems_left(K, P, N))
|
Number of chocolates left after k iterations | Function to find the chocolates left ; Driver code | def results(n, k):
"""
Number of chocolates left after k iterations
"""
return round(pow(n, (1.0 / pow(2, k))))
k = 3
n = 100000000
print("Chocolates left after"),
print(k),
print("iterations are"),
print(int(results(n, k)))
|
Longest subsequence whose average is less than K | Python3 program to perform Q queries to find longest subsequence whose average is less than K ; Function to print the length for evey query ; sort array of N elements ; Array to store average from left ; Sort array of average ; number of queries ; print answer to every... | import bisect
def longest_subsequence(a, n, q, m):
"""
Longest subsequence whose average is less than K
"""
a.sort()
Sum = 0
b = [None] * n
for i in range(0, n):
Sum += a[i]
av = Sum // (i + 1)
b[i] = av + 1
b.sort()
for i in range(0, m):
k = q[i]
... |
Make array elements equal in Minimum Steps | Returns the minimum steps required to make an array of N elements equal , where the first array element equals M ; Corner Case 1 : When N = 1 ; Corner Case 2 : When N = 2 ; Driver Code | def steps(N, M):
"""
Make array elements equal in Minimum Steps
"""
if (N == 1):
return 0
elif (N == 2):
return M
return 2 * M + (N - 3)
N = 4
M = 4
print(steps(N, M))
|
Minimum increment / decrement to make array non | Python3 code to count the change required to convert the array into non - increasing array ; min heap ; Here in the loop we will check that whether the upcoming element of array is less than top of priority queue . If yes then we calculate the difference . After that we... | from queue import PriorityQueue
def decreasing_array(a, n):
"""
Minimum increment / decrement to make array non
"""
ss, dif = (0, 0)
pq = PriorityQueue()
for i in range(n):
tmp = 0
if not pq.empty():
tmp = pq.get()
pq.put(tmp)
if not pq.empty() a... |
Schedule jobs so that each server gets equal load | Function to find new array a ; find sum S of both arrays a and b . ; Single element case . ; This checks whether sum s can be divided equally between all array elements . i . e . whether all elements can take equal value or not . ; Compute possible value of new array ... | def solve(a, b, n):
"""
Schedule jobs so that each server gets equal load
"""
s = 0
for i in range(0, n):
s += a[i] + b[i]
if n == 1:
return a[0] + b[0]
if s % n != 0:
return -1
x = s // n
for i in range(0, n):
if a[i] > x:
return -1
... |
Check if it is possible to survive on Island | function to find the minimum days ; If we can not buy at least a week supply of food during the first week OR We can not buy a day supply of food on the first day then we can 't survive. ; If we can survive then we can buy ceil ( A / N ) times where A is total units of foo... | def survival(S, N, M):
"""
Check if it is possible to survive on Island
"""
if (((N * 6) < (M * 7) and S > 6) or M > N):
print("No")
else:
days = (M * S) / N
if (((M * S) % N) != 0):
days += 1
print("Yes "),
print(days)
S = 10
N = 16
M = 2
surviv... |
Lexicographically largest subsequence such that every character occurs at least k times | Find lexicographically largest subsequence of s [ 0. . n - 1 ] such that every character appears at least k times . The result is filled in t [ ] ; Starting from largest charter ' z ' to 'a ; Counting the frequency of the characte... | def subsequence(s, t, n, k):
"""
Lexicographically largest subsequence such that every character occurs at least k times
"""
last = 0
cnt = 0
new_last = 0
size = 0
string = 'zyxwvutsrqponmlkjihgfedcba'
for ch in string:
cnt = 0
for i in range(last, n):
if... |
Largest permutation after at most k swaps | Function to find the largest permutation after k swaps ; Storing the elements and their index in map ; If number of swaps allowed are equal to number of elements then the resulting permutation will be descending order of given permutation . ; If j is not at it 's best index ;... | def bestpermutation(arr, k, n):
"""
Largest permutation after at most k swaps
"""
h = {}
for i in range(n):
h[arr[i]] = i
if (n <= k):
arr.sort()
arr.reverse()
else:
for j in range(n, 0, -1):
if (k > 0):
initial_index = h[j]
... |
Program for Best Fit algorithm in Memory Management | Function to allocate memory to blocks as per Best fit algorithm ; Stores block id of the block allocated to a process ; pick each process and find suitable blocks according to its size ad assign to it ; Find the best fit block for current process ; If we could find ... | def best_fit(blockSize, m, processSize, n):
"""
Program for Best Fit algorithm in Memory Management
"""
allocation = [-1] * n
for i in range(n):
bestIdx = -1
for j in range(m):
if blockSize[j] >= processSize[i]:
if bestIdx == -1:
bestId... |
Bin Packing Problem ( Minimize number of used Bins ) | Returns number of bins required using first fit online algorithm ; Initialize result ( Count of bins ) ; Create an array to store remaining space in bins there can be at most n bins ; Place items one by one ; Find the first bin that can accommodate weight [ i ] ; I... | def first_fit(weight, n, c):
"""
Bin Packing Problem ( Minimize number of used Bins )
"""
res = 0
bin_rem = [0] * n
for i in range(n):
j = 0
min = c + 1
bi = 0
for j in range(res):
if (bin_rem[j] >= weight[i] and bin_rem[j] - weight[i] < min):
... |
Longest subarray with all even or all odd elements | Function to calculate longest substring with odd or even elements ; Initializing dp [ ] ; Initializing dp [ 0 ] with 1 ; ans will store the final answer ; Traversing the array from index 1 to N - 1 ; Checking both current and previous element is even or odd ; Updatin... | def longest_odd_even_subarray(A, N):
"""
Longest subarray with all even or all odd elements
"""
dp = [0 for i in range(N)]
dp[0] = 1
ans = 1
for i in range(1, N, 1):
if ((A[i] %
2 == 0 and A[i - 1] %
2 == 0) or (A[i] %
2 != 0 and A[i... |
Maximum subsequence sum such that no three are consecutive in O ( 1 ) space | Function to calculate the maximum subsequence sum such that no three elements are consecutive ; when N is 1 , answer would be the only element present ; when N is 2 , answer would be sum of elements ; variable to store sum up to i - 3 ; varia... | def max_sum_wo3_consec(A, N):
"""
Maximum subsequence sum such that no three are consecutive in O ( 1 ) space
"""
if (N == 1):
return A[0]
if (N == 2):
return A[0] + A[1]
third = A[0]
second = third + A[1]
first = max(second, A[1] + A[2])
sum = max(max(third, second),... |
Minimum number of given operations required to reduce a number to 2 | Function to find the minimum number of operations required to reduce n to 2 ; Initialize a dp array ; Handle the base case ; Iterate in the range [ 2 , n ] ; Check if i * 5 <= n ; Check if i + 3 <= n ; Return the result ; Driver code ; Given Input ; ... | def find_min_operations(n):
"""
Minimum number of given operations required to reduce a number to 2
"""
dp = [0 for i in range(n + 1)]
for i in range(n + 1):
dp[i] = 999999
dp[2] = 0
for i in range(2, n + 1):
if (i * 5 <= n):
dp[i * 5] = min(dp[i * 5], dp[i] + 1)
... |
Split array into subarrays such that sum of difference between their maximums and minimums is maximum | Function to find maximum sum of difference between maximums and minimums in the splitted subarrays ; Traverse the array ; Stores the maximum and minimum elements upto the i - th index ; Traverse the range [ 0 , i ] ;... | def get_value(arr, N):
"""
Split array into subarrays such that sum of difference between their maximums and minimums is maximum
"""
dp = [0 for i in range(N)]
for i in range(1, N):
minn = arr[i]
maxx = arr[i]
j = i
while (j >= 0):
minn = min(arr[j], minn)... |
Maximum score possible by removing substrings made up of single distinct character | Initialize a dictionary to store the precomputed results ; Function to calculate the maximum score possible by removing substrings ; If s is present in dp [ ] array ; Base Cases : ; If length of string is 0 ; If length of string is 1 ;... | dp = dict()
def max_score(s, a):
"""
Maximum score possible by removing substrings made up of single distinct character
"""
if s in dp:
return dp[s]
n = len(s)
if n == 0:
return 0
if n == 1:
return a[0]
head = 0
mx = -1
while head < n:
tail = hea... |
Count all unique outcomes possible by performing S flips on N coins | Dimensions of the DP table ; Stores the dp states ; Function to recursively count the number of unique outcomes possible by performing S flips on N coins ; Base Case ; If the count for the current state is not calculated , then calculate it recursive... | size = 100
ans = [[0 for i in range(size)]for j in range(size)]
def number_of_unique_outcomes(n, s):
"""
Count all unique outcomes possible by performing S flips on N coins
"""
if (s < n):
ans[n][s] = 0
elif (n == 1 or n == s):
ans[n][s] = 1
elif (ans[n][s] == 0):
ans[n... |
Minimize removals to remove another string as a subsequence of a given string | Function to print the minimum number of character removals required to remove X as a subsequence from the string str ; Length of the string str ; Length of the string X ; Stores the dp states ; Fill first row of dp [ ] [ ] ; If X [ j ] matc... | def print_minimum_removals(s, X):
"""
Minimize removals to remove another string as a subsequence of a given string
"""
N = len(s)
M = len(X)
dp = [[0 for x in range(M)]for y in range(N)]
for j in range(M):
if (s[0] == X[j]):
dp[0][j] = 1
for i in range(1, N):
... |
Railway Station | TCS CodeVita 2020 | Dp table for memoization ; Function to count the number of ways to N - th station ; Base Cases ; If current state is already evaluated ; Count ways in which train 1 can be chosen ; Count ways in which train 2 can be chosen ; Count ways in which train 3 can be chosen ; Store the cur... | dp = [-1 for i in range(100000)]
def find_ways(x):
"""
Railway Station
"""
if (x < 0):
return 0
if (x == 0):
return 1
if (x == 1):
return 2
if (x == 2):
return 4
if (dp[x] != -1):
return dp[x]
count = find_ways(x - 1)
count += find_ways(x... |
Count N | Function to count binary strings of length N having substring "11" ; Initialize dp [ ] of size N + 1 ; Base Cases ; Stores the first N powers of 2 ; Generate ; Iterate over the range [ 2 , N ] ; Prtotal count of substrings ; Driver Code | def binary_strings(N):
"""
Count N
"""
dp = [0] * (N + 1)
dp[0] = 0
dp[1] = 0
power = [0] * (N + 1)
power[0] = 1
for i in range(1, N + 1):
power[i] = 2 * power[i - 1]
for i in range(2, N + 1):
dp[i] = dp[i - 1] + dp[i - 2] + power[i - 2]
print(dp[N])
if __na... |
Minimize cost of painting N houses such that adjacent houses have different colors | Function to find the minimum cost of coloring the houses such that no two adjacent houses has the same color ; Corner Case ; Auxiliary 2D dp array ; Base Case ; If current house is colored with red the take min cost of previous houses ... | def min_cost(costs, N):
"""
Minimize cost of painting N houses such that adjacent houses have different colors
"""
if (N == 0):
return 0
dp = [[0 for i in range(3)]for j in range(3)]
dp[0][0] = costs[0][0]
dp[0][1] = costs[0][1]
dp[0][2] = costs[0][2]
for i in range(1, N, 1):... |
Count subsequences having average of its elements equal to K | Stores the dp states ; Function to find the count of subsequences having average K ; Base condition ; Three loops for three states ; Recurrence relation ; Stores the sum of dp [ n ] [ j ] [ K * j ] all possible values of j with average K and sum K * j ; Ite... | dp = [[[0 for i in range(1001)]for i in range(101)]for i in range(101)]
def count_average(n, K, arr):
"""
Count subsequences having average of its elements equal to K
"""
global dp
dp[0][0][0] = 1
for i in range(n):
for k in range(n):
for s in range(100):
dp... |
Count ways to remove pairs from a matrix such that remaining elements can be grouped in vertical or horizontal pairs | Function to count ways to remove pairs such that the remaining elements can be arranged in pairs vertically or horizontally ; Store the size of matrix ; If N is odd , then no such pair exists ; Store t... | def numberofpairs(v, k):
"""
Count ways to remove pairs from a matrix such that remaining elements can be grouped in vertical or horizontal pairs
"""
n = len(v)
if (n % 2 == 1):
print(0)
return
ans = 0
dp = [[0 for i in range(2)]for j in range(k)]
for i in range(k):
... |
Maximize sum by selecting X different | Python3 program for the above approach ; Store overlapping subproblems of the recurrence relation ; Function to find maximum sum of at most N with different index array elements such that at most X are from A [ ] , Y are from B [ ] and Z are from C [ ] ; Base Cases ; If the subpr... | import sys
dp = [[[[-1 for i in range(50)]for j in range(50)]
for k in range(50)]for l in range(50)]
def find_max_s(X, Y, Z, n, A, B, C):
"""
Maximize sum by selecting X different
"""
if (X < 0 or Y < 0 or Z < 0):
return -sys .maxsize - 1
if (n < 0):
return 0
if (dp[n][X... |
Minimum operations to transform given string to another by moving characters to front or end | Python3 program for the above approach ; Function that finds the minimum number of steps to find the minimum characters must be moved to convert string s to t ; r = maximum value over all dp [ i ] [ j ] computed so far ; dp [... | dp = [[0] * 1010] * 1010
def solve(s, t):
"""
Minimum operations to transform given string to another by moving characters to front or end
"""
n = len(s)
r = 0
for j in range(0, n):
for i in range(0, n):
dp[i][j] = 0
if (i > 0):
dp[i][j] = max(dp... |
Longest substring whose characters can be rearranged to form a Palindrome | Function to get the length of longest substring whose characters can be arranged to form a palindromic string ; To keep track of the last index of each xor ; Initialize answer with 0 ; Now iterate through each character of the string ; Convert ... | def longest_substring(s:
"""
Longest substring whose characters can be rearranged to form a Palindrome
"""
str, n: int):
index = dict()
answer = 0
mask = 0
index[mask] = -1
for i in range(n):
temp = ord(s[i]) - 97
mask ^= (1 << temp)
... |
Count of N | Function to find count of N - digit numbers with single digit XOR ; dp [ i ] [ j ] stores the number of i - digit numbers with XOR equal to j ; For 1 - 9 store the value ; Iterate till N ; Calculate XOR ; Store in DP table ; Initialize count ; Print answer ; Driver Code ; Given number N ; Function Call | def count_nums(N):
"""
Count of N
"""
dp = [[0 for i in range(16)]for j in range(N)]
for i in range(1, 10):
dp[0][i] = 1
for i in range(1, N):
for j in range(0, 10):
for k in range(0, 16):
xor = j ^ k
dp[i][xor] += dp[i - 1][k]
coun... |
Count of numbers upto M divisible by given Prime Numbers | Function to count the numbers that are divisible by the numbers in the array from range 1 to M ; Initialize the count variable ; Iterate over [ 1 , M ] ; Iterate over array elements arr [ ] ; Check if i is divisible by a [ j ] ; Increment the count ; Return the... | def count(a, M, N):
"""
Count of numbers upto M divisible by given Prime Numbers
"""
cnt = 0
for i in range(1, M + 1):
for j in range(N):
if (i % a[j] == 0):
cnt += 1
break
return cnt
lst = [2, 3, 5, 7]
m = 100
n = len(lst)
print(count(lst, m... |
Count of numbers upto N digits formed using digits 0 to K | Python3 implementation to count the numbers upto N digits such that no two zeros are adjacent ; Function to count the numbers upto N digits such that no two zeros are adjacent ; Condition to check if only one element remains ; If last element is non zero , ret... | dp = [[0] * 10 for j in range(15)]
def solve(n, last, k):
"""
Count of numbers upto N digits formed using digits 0 to K
"""
if (n == 1):
if (last == k):
return (k - 1)
else:
return 1
if (dp[n][last]):
return dp[n][last]
if (last == k):
dp... |
Maximum sum by picking elements from two arrays in order | Set 2 | Function to calculate maximum sum ; Maximum elements that can be chosen from array A ; Maximum elements that can be chosen from array B ; Stores the maximum sum possible ; Fill the dp [ ] for base case when all elements are selected from A [ ] ; Fill th... | def maximum_sum(A, B, length, X, Y):
"""
Maximum sum by picking elements from two arrays in order
"""
l = length
l1 = min(length, X)
l2 = min(length, Y)
dp = [[0 for i in range(l2 + 1)]for i in range(l1 + 1)]
dp[0][0] = 0
max_sum = -10 * 9
for i in range(1, l1 + 1):
dp[i]... |
Min number of operations to reduce N to 0 by subtracting any digits from N | Function to reduce an integer N to Zero in minimum operations by removing digits from N ; Initialise dp [ ] to steps ; Iterate for all elements ; For each digit in number i ; Either select the number or do not select it ; dp [ N ] will give mi... | def reduce_zero(N):
"""
Min number of operations to reduce N to 0 by subtracting any digits from N
"""
dp = [1e9 for i in range(N + 1)]
dp[0] = 0
for i in range(N + 1):
for c in str(i):
dp[i] = min(dp[i], dp[i - (ord(c) - 48)] + 1)
return dp[N]
N = 25
print(reduce_zero(... |
Pentanacci Numbers | Function to print Nth Pentanacci number ; Initialize first five numbers to base cases ; declare a current variable ; Loop to add previous five numbers for each number starting from 5 and then assign first , second , third , fourth to second , third , fourth and curr to fifth respectively ; Driver c... | def printpenta(n):
"""
Pentanacci Numbers
"""
if (n < 0):
return
first = 0
second = 0
third = 0
fourth = 0
fifth = 1
curr = 0
if (n == 0 or n == 1 or n == 2 or n == 3):
print(first)
elif (n == 5):
print(fifth)
else:
for i in range(5, n)... |
Count of binary strings of length N with even set bit count and at most K consecutive 1 s | Python3 program for the above approach ; Table to store solution of each subproblem ; Function to calculate the possible binary strings ; If number of ones is equal to K ; pos : current position Base Case : When n length is trav... | import numpy as np
dp = np.ones(((100002, 21, 3)))
dp = -1 * dp
def possible_binaries(pos, ones, sum, k):
"""
Count of binary strings of length N with even set bit count and at most K consecutive 1 s
"""
if (ones == k):
return 0
if (pos == 0):
return 1 if (sum == 0)else 0
if (d... |
Minimize prize count required such that smaller value gets less prize in an adjacent pair | Function to find the minimum number of required such that adjacent smaller elements gets less number of prizes ; Loop to iterate over every elements of the array ; Loop to find the consecutive smaller elements at left ; Loop to ... | def find_min_prizes(arr, n):
"""
Minimize prize count required such that smaller value gets less prize in an adjacent pair
"""
totalPrizes = 0
for i in range(n):
x = 1
j = i
while (j > 0 and arr[j] > arr[j - 1]):
x += 1
j -= 1
j = i
y =... |
Minimum number of squares whose sum equals to given number N | set 2 | Function for finding minimum square numbers ; arr [ i ] of array arr store minimum count of square number to get i ; sqrNum [ i ] store last square number to get i ; Find minimum count of square number for all value 1 to n ; In worst case it will be... | def min_sqr_num(n):
"""
Minimum number of squares whose sum equals to given number N
"""
arr = [0] * (n + 1)
sqrNum = [0] * (n + 1)
v = []
for i in range(n + 1):
arr[i] = arr[i - 1] + 1
sqrNum[i] = 1
k = 1
while (k * k <= i):
if (arr[i] > arr[i - k... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.