giulio98/xlcost-single-prompt huggingface dataset:
# longest subsequence having difference atmost k | function to find the longest special sequence ; creating a list with all 0 's of size  equal to the length of string ; supporting list with all 0 's of size 26 since  the given string consists  of only lower case alphabets ; converting the ascii value to list indices ; determining the lower bound ; determining the upper bound ; filling the dp array with values ; filling the max_length array with max length of subsequence till now ; return the max length of subsequence ; 
def longest_subseq(n, k, s):
    dp = [0] * n
    max_length = [0] * 26
    for i in range(n):
        curr = ord(s[i]) - ord('a')
        lower = max(0, curr - k)
        upper = min(25, curr + k)
        for j in range(lower, upper + 1):
            dp[i] = max(dp[i], max_length[j] + 1)
        max_length[curr] = max(dp[i], max_length[curr])
    return max(dp)


def main():
    s = "geeksforgeeks"
    n = len(s)
    k = 3
    print(longest_subseq(n, k, s))


main()

# Expected output:
7
# maximum possible array sum after performing the given operation | function to return the maximum possible sum after performing the given operation ; dp vector to store the answer ; base value ; return the maximum sum ; 
def max_sum(a, n):
    dp = [[0 for i in range(2)]for j in range(n + 1)]
    dp[0][0] = 0
    dp[0][1] = -999999
    for i in range(0, n):
        dp[i + 1][0] = max(dp[i][0] + a[i], dp[i][1] - a[i])
        dp[i + 1][1] = max(dp[i][0] - a[i], dp[i][1] + a[i])
    return dp[n][0]


if __name__ == '__main__':
    a = [-10, 5, -4]
    n = len(a)
    print(max_sum(a, n))

# Expected output:
19
# find the number of ways to reach kth step in stair case | python3 implementation of the approach ; function to return the number of ways to reach the kth step ; create the dp array ; broken steps ; calculate the number of ways for the rest of the positions ; if it is a blocked position ; number of ways to get to the ith step ; return the required answer ; 

MOD = 1000000007


def number_of_ways(arr, n, k):
    if (k == 1):
        return 1
    dp = [-1] * (k + 1)
    for i in range(n):
        dp[arr[i]] = 0
    dp[0] = 1
    dp[1] = 1 if (dp[1] == -1)else dp[1]
    for i in range(2, k + 1):
        if (dp[i] == 0):
            continue
        dp[i] = dp[i - 1] + dp[i - 2]
        dp[i] %= MOD
    return dp[k]


if __name__ == "__main__":
    arr = [3]
    n = len(arr)
    k = 6
    print(number_of_ways(arr, n, k))

# Expected output:
4
# minimum number of coins that can generate all the values in the given range | python3 program to find minimum number of coins ; function to find minimum number of coins ; 

import math


def findCount(n):
    return int(math .log(n, 2)) + 1


N = 10
print(findCount(N))

# Expected output:
4
# calculate the number of set bits for every number from 0 to n | python 3 implementation of the approach ; function to find the count of set bits in all the integers from 0 to n ; 
def count(n):
    count = 0
    while (n):
        count += n & 1
        n >>= 1
    return count


def findSetBits(n):
    for i in range(n + 1):
        print(count(i), end=" ")


if __name__ == '__main__':
    n = 5
    findSetBits(n)

# Expected output:
0 1 1 2 1 2
# count number of ways to arrange first n numbers | python3 implementation of the approach ; function to return the count of required arrangements ; create a vector ; store numbers from 1 to n ; to store the count of ways ; initialize flag to true if first element is 1 else false ; checking if the current permutation satisfies the given conditions ; if the current permutation is invalid then set the flag to false ; if valid arrangement ; generate the all permutation ; 

from itertools import permutations


def countWays(n):
    a = []
    i = 1
    while (i <= n):
        a .append(i)
        i += 1
    ways = 0
    for per in list(permutations(a)):
        flag = 1 if (per[0] == 1) else 0

        for i in range(1, n):
            if (abs(per[i] - per[i - 1]) > 2):
                flag = 0

        if (flag):
            ways += 1

    return ways


n = 6
print(countWays(n))

# Expected output:
9
# count number of ways to arrange first n numbers | function to return the count of required arrangements ; create the dp array ; initialize the base cases as explained above ; ( 12 ) as the only possibility ; generate answer for greater values ; dp [ n ] contains the desired answer ; 
def countWays(n):
    dp = [0 for i in range(n + 1)]
    dp[0] = 0
    dp[1] = 1
    dp[2] = 1
    for i in range(3, n + 1):
        dp[i] = dp[i - 1] + dp[i - 3] + 1
    return dp[n]


n = 6
print(countWays(n))

# Expected output:
9
# number of shortest paths to reach every cell from bottom | function to find number of shortest paths ; compute the grid starting from the bottom - left corner ; print the grid ; 
def NumberOfShortestPaths(n, m):
    a = [[0 for i in range(m)]for j in range(n)]
    for i in range(n):
        for j in range(m):
            a[i][j] = 0
    i = n - 1
    while (i >= 0):
        for j in range(m):
            if (j == 0 or i == n - 1):
                a[i][j] = 1
            else:
                a[i][j] = a[i][j - 1] + a[i + 1][j]
        i -= 1
    for i in range(n):
        for j in range(m):
            print(a[i][j], end=" ")
        print("",  end="")


if __name__ == '__main__':
    n = 5
    m = 2
    NumberOfShortestPaths(n, m)

# Expected output:
1 5 1 4 1 3 1 2 1 1
# maximum sum combination from two arrays | function to maximum sum combination from two arrays ; to store dp value ; for loop to calculate the value of dp ; return the required answer ; 
def Max_Sum(arr1, arr2, n):
    dp = [[0 for i in range(2)]for j in range(n)]
    for i in range(n):
        if (i == 0):
            dp[i][0] = arr1[i]
            dp[i][1] = arr2[i]
            continue
        else:
            dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + arr1[i])
            dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + arr2[i])
    return max(dp[n - 1][0], dp[n - 1][1])


if __name__ == '__main__':
    arr1 = [9, 3, 5, 7, 3]
    arr2 = [5, 8, 1, 4, 5]
    n = len(arr1)
    print(Max_Sum(arr1, arr2, n))

# Expected output:
29
# partition the array in k segments such that bitwise and of individual segment sum is maximized | function to check whether a k segment partition is possible such that bitwise and is 'mask ; dp [ i ] [ j ] stores whether it is possible to partition first i elements into j segments such that all j segments are 'good ; initialising dp ; filling dp in bottom - up manner ; finding a cut such that first l elements can be partitioned into j - 1 ' good ' segments and arr [ l + 1 ] + ... + arr [ i ] is a ' good ' segment ; function to find maximum possible and ; array to store prefix sums ; maximum no of bits in the possible answer ; this will store the final answer ; constructing answer greedily selecting from the higher most bit ; checking if array can be partitioned such that the bitwise and is ans | ( 1 << i ) ; if possible , update the answer ; return the final answer ; 
def checkpossible(mask, arr, prefix, n, k):
    dp = [[0 for i in range(k + 1)]for i in range(n + 1)]
    dp[0][0] = 1
    for i in range(1, n + 1):
        for j in range(1, k + 1):
            for l in range(i - 1, -1, -1):
                if (dp[l][j - 1] and (((prefix[i] - prefix[l]) & mask) == mask)):
                    dp[i][j] = 1
                    break
    return dp[n][k]


def Partition(arr, n, k):
    prefix = [0 for i in range(n + 1)]
    for i in range(1, n + 1):
        prefix[i] = prefix[i - 1] + arr[i]
    LOGS = 20
    ans = 0
    for i in range(LOGS, -1, -1):
        if (checkpossible(ans | (1 << i), arr, prefix, n, k)):
            ans = ans | (1 << i)
    return ans


arr = [0, 1, 2, 7, 10, 23, 21, 6, 8, 7, 3]
k = 2
n = len(arr) - 1
print(Partition(arr, n, k))

# Expected output:
41
# minimum time required to rot all oranges | dynamic programming | python 3 implementation of the approach ; dp table to memoize the values ; visited array to keep track of visited nodes in order to avoid infinite loops ; function to return the minimum of four numbers ; function to return the minimum distance to any rotten orange from [ i , j ] ; if i , j lie outside the array ; if 0 then it can 't lead to  any path so return int_max ; if 2 then we have reached our rotten oranges so return from here ; if this node is already visited then return to avoid infinite loops ; mark the current node as visited ; check in all four possible directions ; take the minimum of all ; if result already exists in the table check if min_value is less than existing value ; function to return the minimum time required to rot all the oranges ; calculate the minimum distances to any rotten orange from all the fresh oranges ; pick the maximum distance of fresh orange to some rotten orange ; if all oranges can be rotten ; 

C = 5
R = 3
INT_MAX = 10000000
table = [[0 for i in range(C)]for j in range(R)]
visited = [[0 for i in range(C)]for j in range(R)]


def min(p, q, r, s):
    if (p < q):
        temp1 = p
    else:
        temp1 = q
    if (r < s):
        temp2 = r
    else:
        temp2 = s
    if (temp1 < temp2):
        return temp1
    return temp2


def Distance(arr, i, j):
    if (i >= R or j >= C or i < 0 or j < 0):
        return INT_MAX
    elif (arr[i][j] == 0):
        table[i][j] = INT_MAX
        return INT_MAX
    elif (arr[i][j] == 2):
        table[i][j] = 0
        return 0
    elif (visited[i][j]):
        return INT_MAX
    else:
        visited[i][j] = 1
        temp1 = Distance(arr, i + 1, j)
        temp2 = Distance(arr, i - 1, j)
        temp3 = Distance(arr, i, j + 1)
        temp4 = Distance(arr, i, j - 1)
        min_value = 1 + min(temp1, temp2, temp3, temp4)
        if table[i][j] > 0 and table[i][j] < INT_MAX:
            if min_value < table[i][j]:
                table[i][j] = min_value
        else:
            table[i][j] = min_value
        visited[i][j] = 0
    return table[i][j]


def minTime(arr):
    max = 0
    for i in range(R):
        for j in range(C):
            if (arr[i][j] == 1):
                Distance(arr, i, j)
    for i in range(R):
        for j in range(C):
            if (arr[i][j] == 1 and table[i][j] > max):
                max = table[i][j]
    if (max < INT_MAX):
        return max
    return -1


if __name__ == '__main__':
    arr = [[2, 1, 0, 2, 1], [0, 0, 1, 2, 1], [1, 0, 0, 2, 1]]
    print(minTime(arr))

# Expected output:
-1
# maximum sum of non | python3 program to implement above approach ; variable to store states of dp ; variable to check if a given state has been solved ; function to find the maximum sum subsequence such that no two elements are adjacent ; base case ; to check if a state has been solved ; variable to store prefix sum for sub - array { i , j } ; required recurrence relation ; returning the value ; 

maxLen = 10
dp = [0] * maxLen
visit = [0] * maxLen


def maxSum(arr, i, n, k):
    if (i >= n):
        return 0
    if (visit[i]):
        return dp[i]
    visit[i] = 1
    tot = 0
    dp[i] = maxSum(arr, i + 1, n, k)
    j = i
    while (j < i + k and j < n):
        tot += arr[j]
        dp[i] = max(dp[i], tot + maxSum(arr, j + 2, n, k))
        j += 1
    return dp[i]


if __name__ == "__main__":
    arr = [-1, 2, -3, 4, 5]
    k = 2
    n = len(arr)
    print(maxSum(arr, 0, n, k))

# Expected output:
11
# maximum subset sum such that no two elements in set have same digit in them | python3 implementation of above approach ; function to create mask for every number ; recursion for filling dp array ; base condition ; recurrence relation ; function to find maximum subset sum ; initialize dp array ; iterate over all possible masks of 10 bit number ; 

dp = [0] * 1024


def get_binary(u):
    ans = 0
    while (u):
        rem = u % 10
        ans |= (1 << rem)
        u //= 10
    return ans


def recur(u, array, n):
    if (u == 0):
        return 0
    if (dp[u] != -1):
        return dp[u]
    temp = 0
    for i in range(n):
        mask = get_binary(array[i])
        if mask == u:
            dp[u] = max(max(0, dp[u ^ mask]) + array[i], dp[u])
    return dp[u]


def solve(array, n):
    i = 0
    while (i < (1 << 10)):
        dp[i] = -1
        i += 1
    ans = 0
    i = 0
    while (i < (1 << 10)):
        ans = max(ans, recur(i, array, n))
        i += 1
    return ans


if __name__ == "__main__":
    array = [22, 132, 4, 45, 12, 223]
    n = len(array)
    print(solve(array, n))

# Expected output:
223
# find maximum topics to prepare in order to pass the exam | python3 implementation of the approach ; function to return the maximum marks by considering topics which can be completed in the given time duration ; if we are given 0 time then nothing can be done so all values are 0 ; if we are given 0 topics then the time required will be 0 for sure ; calculating the maximum marks that can be achieved under the given time constraints ; if time taken to read that topic is more than the time left now at position j then do no read that topic ; two cases arise : 1 ) considering current topic 2 ) ignoring current topic we are finding maximum of ( current topic weightage + topics which can be done in leftover time - current topic time ) and ignoring current topic weightage sum ; moving upwards in table from bottom right to calculate the total time taken to read the topics which can be done in given time and have highest weightage sum ; it means we have not considered reading this topic for max weightage sum ; adding the topic time ; evaluating the left over time after considering this current topic ; one topic completed ; it contains the maximum weightage sum formed by considering the topics ; condition when exam cannot be passed ; return the marks that can be obtained after passing the exam ; 

import numpy as np


def MaximumMarks(marksarr, timearr, h, n, p):
    no_of_topics = n + 1
    total_time = h + 1
    T = np .zeros((no_of_topics, total_time))
    for i in range(no_of_topics):
        T[i][0] = 0
    for j in range(total_time):
        T[0][j] = 0
    for i in range(1, no_of_topics):
        for j in range(1, total_time):
            if (j < timearr[i]):
                T[i][j] = T[i - 1][j]
            else:
                T[i][j] = max(marksarr[i] + T[i - 1]
                              [j - timearr[i]], T[i - 1][j])
    i = no_of_topics - 1
    j = total_time - 1
    sum = 0
    while (i > 0 and j > 0):
        if (T[i][j] == T[i - 1][j]):
            i -= 1
        else:
            sum += timearr[i]
            j -= timearr[i]
            i -= 1
    marks = T[no_of_topics - 1][total_time - 1]
    if (marks < p):
        return -1
    return sum


if __name__ == "__main__":
    n = 4
    h = 10
    p = 10
    marksarr = [0, 6, 4, 2, 8]
    timearr = [0, 4, 6, 2, 7]
    print(MaximumMarks(marksarr, timearr, h, n, p))

# Expected output:
10
# minimize the number of steps required to reach the end of the array | python3 implementation of the above approach ; variable to store states of dp ; variable to check if a given state has been solved ; function to find the minimum number of steps required to reach the end of the array ; base case ; to check if a state has been solved ; required recurrence relation ; returning the value ; 

maxLen = 10
maskLen = 130
dp = [[0 for i in range(maskLen)]for i in range(maxLen)]
v = [[False for i in range(maskLen)]for i in range(maxLen)]


def minSteps(arr, i, mask, n):
    if (i == n - 1):
        return 0
    if (i > n - 1 or i < 0):
        return 9999999
    if ((mask >> i) & 1):
        return 9999999
    if (v[i][mask]):
        return dp[i][mask]
    v[i][mask] = True
    dp[i][mask] = 1 + min(minSteps(arr,
                                   i - arr[i],
                                   (mask | (1 << i)),
                                   n),
                          minSteps(arr,
                                   i + arr[i],
                                   (mask | (1 << i)),
                                   n))
    return dp[i][mask]


arr = [1, 2, 2, 2, 1, 1]
n = len(arr)
ans = minSteps(arr, 0, 0, n)
if (ans >= 9999999):
    print(-1)
else:
    print(ans)

# Expected output:
3
# optimal strategy for a game | set 2 | python3 program to find out maximum value from a given sequence of coins ; for both of your choices , the opponent gives you total sum minus maximum of his value ; returns optimal value possible that a player can collect from an array of coins of size n . note than n must be even ; 
def oSRec(arr, i, j, Sum):
    if (j == i + 1):
        return max(arr[i], arr[j])
    return max(
        (Sum -
         oSRec(
             arr,
             i +
             1,
             j,
             Sum -
             arr[i])),
        (Sum -
         oSRec(
             arr,
             i,
             j -
             1,
             Sum -
             arr[j])))


def optimalStrategyOfGame(arr, n):
    Sum = 0
    Sum = sum(arr)
    return oSRec(arr, 0, n - 1, Sum)


arr1 = [8, 15, 3, 7]
n = len(arr1)
print(optimalStrategyOfGame(arr1, n))
arr2 = [2, 2, 2, 2]
n = len(arr2)
print(optimalStrategyOfGame(arr2, n))
arr3 = [20, 30, 2, 2, 2, 10]
n = len(arr3)
print(optimalStrategyOfGame(arr3, n))

# Expected output:
22
4
42
# minimum number of sub | function that returns true if n is a power of 5 ; function to return the decimal value of binary equivalent ; function to return the minimum cuts required ; allocating memory for dp [ ] array ; from length 1 to n ; if previous character is '0' then ignore to avoid number with leading 0 s . ; ignore s [ j ] = '0' starting numbers ; number formed from s [ j ... . i ] ; check for power of 5 ; assigning min value to get min cut possible ; ( n + 1 ) to check if all the strings are traversed and no divisible by 5 is obtained like 000000 ; 
def ispower(n):
    if (n < 125):
        return (n == 1 or n == 5 or n == 25)
    if (n % 125 != 0):
        return 0
    else:
        return ispower(n // 125)


def number(s, i, j):
    ans = 0
    for x in range(i, j):
        ans = ans * 2 + (ord(s[x]) - ord('0'))
    return ans


def minCuts(s, n):
    dp = [n + 1 for i in range(n + 1)]
    dp[0] = 0
    for i in range(1, n + 1):
        if (s[i - 1] == '0'):
            continue
        for j in range(i):
            if (s[j] == '0'):
                continue
            num = number(s, j, i)
            if (not ispower(num)):
                continue
            dp[i] = min(dp[i], dp[j] + 1)
    if dp[n] < n + 1:
        return dp[n]
    else:
        return -1


if __name__ == "__main__":
    s = "101101101"
    n = len(s)
    print(minCuts(s, n))

# Expected output:
3
# minimum number of cubes whose sum equals to given number n | function to return the minimum number of cubes whose sum is k ; if k is less than the 2 ^ 3 ; initialize with the maximum number of cubes required ; 
def MinOfCubed(k):
    if (k < 8):
        return k
    res = k
    for i in range(1, k + 1):
        if ((i * i * i) > k):
            return res
        res = min(res, MinOfCubed(k - (i * i * i)) + 1)
    return res


num = 15
print(MinOfCubed(num))

# Expected output:
8
# minimum number of cubes whose sum equals to given number n | python implementation of the approach ; function to return the minimum number of cubes whose sum is k ; while current perfect cube is less than current element ; if i is a perfect cube ; i = ( i - 1 ) + 1 ^ 3 ; next perfect cube ; re - initialization for next element ; 

import sys


def MinOfCubedDP(k):
    DP = [0] * (k + 1)
    j = 1
    t = 1
    DP[0] = 0
    for i in range(1, k + 1):
        DP[i] = sys .maxsize
        while (j <= i):
            if (j == i):
                DP[i] = 1
            elif (DP[i] > DP[i - j]):
                DP[i] = DP[i - j] + 1
            t += 1
            j = t * t * t
        t = j = 1
    return DP[k]


num = 15
print(MinOfCubedDP(num))

# Expected output:
8
# maximum subarray sum after inverting at most two elements | function to return the maximum required sub - array sum ; creating one based indexing ; 2d array to contain solution for each step ; case 1 : choosing current or ( current + previous ) whichever is smaller ; case 2 : ( a ) altering sign and add to previous case 1 or value 0 ; case 2 : ( b ) adding current element with previous case 2 and updating the maximum ; case 3 : ( a ) altering sign and add to previous case 2 ; case 3 : ( b ) adding current element with previous case 3 ; updating the maximum value of variable ans ; return the final solution ; 
def maxSum(a, n):
    ans = 0
    arr = [0] * (n + 1)
    for i in range(1, n + 1):
        arr[i] = a[i - 1]
    dp = [[0 for i in range(3)]for j in range(n + 1)]
    for i in range(0, n + 1):
        dp[i][0] = max(arr[i], dp[i - 1][0] + arr[i])
        dp[i][1] = max(0, dp[i - 1][0]) - arr[i]
        if i >= 2:
            dp[i][1] = max(dp[i][1], dp[i - 1][1] + arr[i])
        if i >= 2:
            dp[i][2] = dp[i - 1][1] - arr[i]
        if i >= 3:
            dp[i][2] = max(dp[i][2], dp[i - 1][2] + arr[i])
        ans = max(ans, dp[i][0])
        ans = max(ans, dp[i][1])
        ans = max(ans, dp[i][2])
    return ans


if __name__ == "__main__":
    arr = [-5, 3, 2, 7, -8, 3, 7, -9, 10, 12, -6]
    n = len(arr)
    print(maxSum(arr, n))

# Expected output:
61
# maximum sum possible for a sub | function to return the maximum sum possible ; dp [ i ] represent the maximum sum so far after reaching current position i ; initialize dp [ 0 ] ; initialize the dp values till k since any two elements included in the sub - sequence must be atleast k indices apart , and thus first element and second element will be k indices apart ; fill remaining positions ; return the maximum sum ; 
def maxSum(arr, k, n):
    if (n == 0):
        return 0
    if (n == 1):
        return arr[0]
    if (n == 2):
        return max(arr[0], arr[1])
    dp = [0] * n
    dp[0] = arr[0]
    for i in range(1, k + 1):
        dp[i] = max(arr[i], dp[i - 1])
    for i in range(k + 1, n):
        dp[i] = max(arr[i], dp[i - (k + 1)] + arr[i])
    max_element = max(dp)
    return max_element


if __name__ == "__main__":
    arr = [6, 7, 1, 3, 8, 2, 4]
    n = len(arr)
    k = 2
    print(maxSum(arr, k, n))

# Expected output:
15
# minimum cost to form a number x by adding up powers of 2 | function to return the minimum cost ; re - compute the array ; add answers for set bits ; if bit is set ; increase the counter ; right shift the number ; 
def MinimumCost(a, n, x):
    for i in range(1, n, 1):
        a[i] = min(a[i], 2 * a[i - 1])
    ind = 0
    sum = 0
    while (x):
        if (x & 1):
            sum += a[ind]
        ind += 1
        x = x >> 1
    return sum


if __name__ == '__main__':
    a = [20, 50, 60, 90]
    x = 7
    n = len(a)
    print(MinimumCost(a, n, x))

# Expected output:
120
# ways to form an array having integers in given range such that total sum is divisible by 2 | function to return the number of ways to form an array of size n such that sum of all elements is divisible by 2 ; represents first and last numbers of each type ( modulo 0 and 1 ) ; count of numbers of each type between range ; base cases ; ways to form array whose sum upto i numbers modulo 2 is 0 ; ways to form array whose sum upto i numbers modulo 2 is 1 ; return the required count of ways ; 
def countWays(n, l, r):
    tL, tR = l, r
    L = [0 for i in range(2)]
    R = [0 for i in range(2)]
    L[l % 2] = l
    R[r % 2] = r
    l += 1
    r -= 1
    if (l <= tR and r >= tL):
        L[l % 2], R[r % 2] = l, r
    cnt0, cnt1 = 0, 0
    if (R[0] and L[0]):
        cnt0 = (R[0] - L[0]) // 2 + 1
    if (R[1] and L[1]):
        cnt1 = (R[1] - L[1]) // 2 + 1
    dp = [[0 for i in range(2)]for i in range(n + 1)]
    dp[1][0] = cnt0
    dp[1][1] = cnt1
    for i in range(2, n + 1):
        dp[i][0] = (cnt0 * dp[i - 1][0] + cnt1 * dp[i - 1][1])
        dp[i][1] = (cnt0 * dp[i - 1][1] + cnt1 * dp[i - 1][0])
    return dp[n][0]


n, l, r = 2, 1, 3
print(countWays(n, l, r))

# Expected output:
5