giulio98/xlcost-single-prompt huggingface dataset:
# maximum sum alternating subsequence | return sum of maximum sum alternating sequence starting with arr [ 0 ] and is first decreasing . ; handling the edge case ; stores sum of decreasing and increasing sub - sequence ; store sum of increasing and decreasing sun - sequence ; as per question , first element must be part of solution . ; traverse remaining elements of array ; if current sub - sequence is decreasing the update dec [ j ] if needed . dec [ i ] by current inc [ j ] + arr [ i ] ; revert the flag , if first decreasing is found ; if next element is greater but flag should be 1 i . e . this element should be counted after the first decreasing element gets counted ; if current sub - sequence is increasing then update inc [ i ] ; find maximum sum in b / w inc [ ] and dec [ ] ; return maximum sum alternate sun - sequence ; 
def maxAlternateSum(arr, n):
    if (n == 1):
        return arr[0]
    min = arr[0]
    for i in range(1, n):
        if (min > arr[i]):
            min = arr[i]
    if (arr[0] == min):
        return arr[0]
    dec = [0 for i in range(n + 1)]
    inc = [0 for i in range(n + 1)]
    dec[0] = inc[0] = arr[0]
    flag = 0
    for i in range(1, n):
        for j in range(i):
            if (arr[j] > arr[i]):
                dec[i] = max(dec[i], inc[j] + arr[i])
                flag = 1
            elif (arr[j] < arr[i] and flag == 1):
                inc[i] = max(inc[i], dec[j] + arr[i])
    result = -2147483648
    for i in range(n):
        if (result < inc[i]):
            result = inc[i]
        if (result < dec[i]):
            result = dec[i]
    return result


arr = [8, 2, 3, 5, 7, 9, 10]
n = len(arr)
print("Maximum sum = ", maxAlternateSum(arr, n))

# Expected output:
Maximum sum =  25
# padovan sequence | function to calculate padovan number p ( n ) ; 0 th , 1 st and 2 nd number of the series are 1 ; 
def pad(n):
    pPrevPrev, pPrev, pCurr, pNext = 1, 1, 1, 1
    for i in range(3, n + 1):
        pNext = pPrevPrev + pPrev
        pPrevPrev = pPrev
        pPrev = pCurr
        pCurr = pNext
    return pNext


print(pad(12))

# Expected output:
21
# find length of the largest region in boolean matrix | a function to check if a given cell ( row , col ) can be included in dfs ; row number is in range , column number is in range and value is 1 and not yet visited ; a utility function to do dfs for a 2d boolean matrix . it only considers the 8 neighbours as adjacent vertices ; these arrays are used to get row and column numbers of 8 neighbours of a given cell ; mark this cell as visited ; recur for all connected neighbours ; increment region length by one ; the main function that returns largest length region of a given boolean 2d matrix ; make a bool array to mark visited cells . initially all cells are unvisited ; initialize result as 0 and travesle through the all cells of given matrix ; if a cell with value 1 is not ; visited yet , then new region found ; maximum region ; 
def isSafe(M, row, col, visited):
    global ROW, COL
    return ((row >= 0) and (row < ROW) and (col >= 0) and (
        col < COL) and (M[row][col] and not visited[row][col]))


def DFS(M, row, col, visited, count):
    rowNbr = [-1, -1, -1, 0, 0, 1, 1, 1]
    colNbr = [-1, 0, 1, -1, 1, -1, 0, 1]
    visited[row][col] = True
    for k in range(8):
        if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited)):
            count[0] += 1
            DFS(M, row + rowNbr[k], col + colNbr[k], visited, count)


def largestRegion(M):
    global ROW, COL
    visited = [[0] * COL for i in range(ROW)]
    result = -999999999999
    for i in range(ROW):
        for j in range(COL):
            if (M[i][j] and not visited[i][j]):
                count = [1]
                DFS(M, i, j, visited, count)
                result = max(result, count[0])
    return result


ROW = 4
COL = 5
M = [[0, 0, 1, 1, 0], [1, 0, 1, 1, 0], [0, 1, 0, 0, 0], [0, 0, 0, 0, 1]]
print(largestRegion(M))

# Expected output:
6
# lucas numbers | iterative function ; declaring base values for positions 0 and 1 ; generating number ; 
def lucas(n):
    a = 2
    b = 1
    if (n == 0):
        return a
    for i in range(2, n + 1):
        c = a + b
        a = b
        b = c
    return b


n = 9
print(lucas(n))

# Expected output:
76
# recursively break a number in 3 parts to get maximum sum | a dynamic programming based python program to find maximum sum by recursively breaking a number in 3 parts . ; function to find the maximum sum ; base conditions ; fill in bottom - up manner using recursive formula . ; 

MAX = 1000000


def breakSum(n):
    dp = [0] * (n + 1)
    dp[0] = 0
    dp[1] = 1
    for i in range(2, n + 1):
        dp[i] = max(dp[int(i / 2)] + dp[int(i / 3)] + dp[int(i / 4)], i)
    return dp[n]


n = 24
print(breakSum(n))

# Expected output:
27
# longest repeating and non | returns the longest repeating non - overlapping substring in str ; building table in bottom - up manner ; ( j - i ) > lcsre [ i - 1 ] [ j - 1 ] to remove overlapping ; updating maximum length of the substring and updating the finishing index of the suffix ; if we have non - empty result , then insert all characters from first character to last character of string ; 
def longestRepeatedSubstring(str):
    n = len(str)
    LCSRe = [[0 for x in range(n + 1)]for y in range(n + 1)]
    res = ""
    res_length = 0
    index = 0
    for i in range(1, n + 1):
        for j in range(i + 1, n + 1):
            if (str[i - 1] == str[j - 1] and LCSRe[i - 1][j - 1] < (j - i)):
                LCSRe[i][j] = LCSRe[i - 1][j - 1] + 1
                if (LCSRe[i][j] > res_length):
                    res_length = LCSRe[i][j]
                    index = max(i, index)
            else:
                LCSRe[i][j] = 0
    if (res_length > 0):
        for i in range(index - res_length + 1, index + 1):
            res = res + str[i - 1]
    return res


if __name__ == "__main__":
    str = "geeksforgeeks"
    print(longestRepeatedSubstring(str))

# Expected output:
geeks
# minimum cost to fill given weight in a bag | python3 program to find minimum cost to get exactly w kg with given packets ; returns the best obtainable price for a rod of length n and price [ ] as prices of different pieces ; build the table val [ ] in bottom up manner and return the last entry from the table ; 

import sys


def minCost(cost, n):
    dp = [0 for i in range(n + 1)]
    for i in range(1, n + 1):
        min_cost = sys .maxsize
        for j in range(i):
            if j < len(cost) and cost[j] != -1:
                min_cost = min(min_cost, cost[j] + dp[i - j - 1])
        dp[i] = min_cost
    return dp[n]


cost = [10, -1, -1, -1, -1]
W = len(cost)
print(minCost(cost, W))

# Expected output:
50
# printing maximum sum increasing subsequence | utility function to calculate sum of all vector elements ; function to construct maximum sum increasing subsequence ; l [ i ] - the maximum sum increasing subsequence that ends with arr [ i ] ; l [ 0 ] is equal to arr [ 0 ] ; start from index 1 ; for every j less than i ; l [ i ] = { maxsum ( l [ j ] ) } + arr [ i ] where j < i and arr [ j ] < arr [ i ] ; l [ i ] ends with arr [ i ] ; l [ i ] now stores maximum sum increasing subsequence of arr [ 0. . i ] that ends with arr [ i ] ;  ; find max ; max will contain result ; 
def findSum(arr):
    summ = 0
    for i in arr:
        summ += i
    return summ


def printMaxSumIS(arr, n):
    L = [[]for i in range(n)]
    L[0].append(arr[0])
    for i in range(1, n):
        for j in range(i):
            if ((arr[i] > arr[j]) and (findSum(L[i]) < findSum(L[j]))):
                for e in L[j]:
                    if e not in L[i]:
                        L[i].append(e)
        L[i].append(arr[i])
    res = L[0]
    for x in L:
        if (findSum(x) > findSum(res)):
            res = x
    for i in res:
        print(i, end=" ")


arr = [3, 2, 6, 4, 5, 1]
n = len(arr)
printMaxSumIS(arr, n)

# Expected output:
3 4 5
# construction of longest increasing subsequence ( lis ) and printing lis sequence | utility function to print lis ; function to construct and print longest increasing subsequence ; l [ i ] - the longest increasing sub - sequence ends with arr [ i ] ; l [ 0 ] is equal to arr [ 0 ] ; start from index 1 ; do for every j less than i ; l [ i ] = { max ( l [ j ] ) } + arr [ i ] where j < i and arr [ j ] < arr [ i ] ; l [ i ] ends with arr [ i ] ; l [ i ] now stores increasing sub - sequence of arr [ 0. . i ] that ends with arr [ i ] ; lis will be max of all increasing sub - sequences of arr ; max will contain lis ; 
def printLIS(arr: list):
    for x in arr:
        print(x, end=" ")
    print()


def constructPrintLIS(arr: list, n: int):
    l = [[]for i in range(n)]
    l[0].append(arr[0])
    for i in range(1, n):
        for j in range(i):
            if arr[i] > arr[j] and (len(l[i]) < len(l[j]) + 1):
                l[i] = l[j].copy()
        l[i].append(arr[i])
    maxx = l[0]
    for x in l:
        if len(x) > len(maxx):
            maxx = x
    printLIS(maxx)


if __name__ == "__main__":
    arr = [3, 2, 6, 4, 5, 1]
    n = len(arr)
    constructPrintLIS(arr, n)

# Expected output:
2 4 5
# find if string is k | returns length of lcs for x [ 0. . m - 1 ] , y [ 0. . n - 1 ] ; following steps build l [ m + 1 ] [ n + 1 ] in bottom up fashion . note that l [ i ] [ j ] contains length of lcs of x [ 0. . i - 1 ] and y [ 0. . j - 1 ] ; l [ m ] [ n ] contains length of lcs for x and y ; find if given string is k - palindrome or not ; find reverse of string ; find longest palindromic subsequence of given string ; if the difference between longest palindromic subsequence and the original string is less than equal to k , then the string is k - palindrome ;  ; 
def lcs(X, Y, m, n):
    L = [[0] * (n + 1)for _ in range(m + 1)]
    for i in range(m + 1):
        for j in range(n + 1):
            if not i or not j:
                L[i][j] = 0
            elif X[i - 1] == Y[j - 1]:
                L[i][j] = L[i - 1][j - 1] + 1
            else:
                L[i][j] = max(L[i - 1][j], L[i][j - 1])
    return L[m][n]


def isKPal(string, k):
    n = len(string)
    revStr = string[::-1]
    lps = lcs(string, revStr, n, n)
    return (n - lps <= k)


string = "abcdeca"
k = 2
print("Yes"if isKPal(string, k)else "No")

# Expected output:
Yes
# wildcard pattern matching | function that matches input strr with given wildcard pattern ; empty pattern can only match with empty string ; lookup table for storing results of subproblems ; empty pattern can match with empty string ; only ' * ' can match with empty string ; fill the table in bottom - up fashion ; two cases if we see a ' * ' a ) we ignore a * atm character and move to next character in the pattern , i . e . , a * atm indicates an empty sequence . b ) ' * ' character matches with ith character in input ; current characters are considered as matching in two cases ( a ) current character of pattern is ' ? ' ( b ) characters actually match ; if characters don 't match ; 
def strrmatch(strr, pattern, n, m):
    if (m == 0):
        return (n == 0)
    lookup = [[False for i in range(m + 1)]for j in range(n + 1)]
    lookup[0][0] = True
    for j in range(1, m + 1):
        if (pattern[j - 1] == '*'):
            lookup[0][j] = lookup[0][j - 1]
    for i in range(1, n + 1):
        for j in range(1, m + 1):
            if (pattern[j - 1] == '*'):
                lookup[i][j] = lookup[i][j - 1] or lookup[i - 1][j]
            elif (pattern[j - 1] == '?' or strr[i - 1] == pattern[j - 1]):
                lookup[i][j] = lookup[i - 1][j - 1]
            else:
                lookup[i][j] = False
    return lookup[n][m]


strr = "baaabab"
pattern = "*****ba*****ab"
if (strrmatch(strr, pattern, len(strr), len(pattern))):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# find if string is k | find if given string is k - palindrome or not ; if first string is empty , the only option is to remove all characters of second string ; if second string is empty , the only option is to remove all characters of first string ; if last characters of two strings are same , ignore last characters and get count for remaining strings . ; if last characters are not same , 1. remove last char from str1 and recur for m - 1 and n 2. remove last char from str2 and recur for m and n - 1 take minimum of above two operations res = 1 + min ( iskpalrec ( str1 , str2 , m - 1 , n ) , remove from str1 ( iskpalrec ( str1 , str2 , m , n - 1 ) ) ) remove from str2 ; returns true if str is k palindrome . ; 
def isKPalRec(str1, str2, m, n):
    if not m:
        return n
    if not n:
        return m
    if str1[m - 1] == str2[n - 1]:
        return isKPalRec(str1, str2, m - 1, n - 1)
    res = 1 + min(isKPalRec(str1, str2, m-1, n),
                  (isKPalRec(str1, str2, m, n-1)))
    return res


def isKPal(string, k):
    revStr = string[::-1]
    l = len(string)
    return (isKPalRec(string, revStr, l, l) <= k * 2)


string = "acdcb"
k = 2
print("Yes" if isKPal(string, k) else "No")

# Expected output:
Yes
# minimum time to finish tasks without skipping two consecutive | arr [ ] represents time taken by n given tasks ; corner cases ; initialize value for the case when there is only one task in task list . first task is included ; first task is exluded ; process remaining n - 1 tasks ; time taken if current task is included there are two possibilities ( a ) previous task is also included ( b ) previous task is not included ; time taken when current task is not included . there is only one possibility that previous task is also included . ; update incl and excl for next iteration ; return maximum of two values for last task ; 
def minTime(arr, n):
    if (n <= 0):
        return 0
    incl = arr[0]
    excl = 0
    for i in range(1, n):
        incl_new = arr[i] + min(excl, incl)
        excl_new = incl
        incl = incl_new
        excl = excl_new
    return min(incl, excl)


arr1 = [10, 5, 2, 7, 10]
n1 = len(arr1)
print(minTime(arr1, n1))

arr2 = [10, 5, 7, 10]
n2 = len(arr2)
print(minTime(arr2, n2))

arr3 = [10, 5, 2, 4, 8, 6, 7, 10]
n3 = len(arr3)
print(minTime(arr3, n3))

# Expected output:
12
12
22
# matrix exponentiation | a utility function to multiply two matrices a [ ] [ ] and b [ ] [ ] . multiplication result is stored back in b [ ] [ ] ; creating an auxiliary matrix to store elements of the multiplication matrix ; storing the multiplication result in a [ ] [ ] ; updating our matrix ; function to compute f raise to power n - 2. ; multiply it with initial values i . e with f ( 0 ) = 0 , f ( 1 ) = 1 , f ( 2 ) = 1 ; multiply it with initial values i . e with f ( 0 ) = 0 , f ( 1 ) = 1 , f ( 2 ) = 1 ; return n 'th term of a series defined using below recurrence relation. f(n) is defined as f(n) = f(n-1) + f(n-2) + f(n-3), n>=3 base cases : f(0) = 0, f(1) = 1, f(2) = 1 ; 
def multiply(a, b):
    mul = [[0 for x in range(3)]for y in range(3)]
    for i in range(3):
        for j in range(3):
            mul[i][j] = 0
            for k in range(3):
                mul[i][j] += a[i][k] * b[k][j]
    for i in range(3):
        for j in range(3):
            a[i][j] = mul[i][j]
    return a


def power(F, n):
    M = [[1, 1, 1], [1, 0, 0], [0, 1, 0]]
    if (n == 1):
        return F[0][0] + F[0][1]
    power(F, int(n / 2))
    F = multiply(F, F)
    if (n % 2 != 0):
        F = multiply(F, M)
    return F[0][0] + F[0][1]


def findNthTerm(n):
    F = [[1, 1, 1], [1, 0, 0], [0, 1, 0]]
    return power(F, n - 2)


n = 5
print("F(5) is", findNthTerm(n))

# Expected output:
F(5) is 7
# count number of ways to fill a " n ▁ x ▁ 4" grid using "1 ▁ x ▁ 4" tiles | returns count of count of ways to place 1 x 4 tiles on n x 4 grid . ; create a table to store results of subproblems dp [ i ] stores count of ways for i x 4 grid . ; fill the table from d [ 1 ] to dp [ n ] ; base cases ; dp ( i - 1 ) : place first tile horizontally dp ( n - 4 ) : place first tile vertically which means 3 more tiles have to be placed vertically . ; 
def count(n):
    dp = [0 for _ in range(n + 1)]
    for i in range(1, n + 1):
        if i <= 3:
            dp[i] = 1
        elif i == 4:
            dp[i] = 2
        else:
            dp[i] = dp[i - 1] + dp[i - 4]
    return dp[n]


n = 5
print("Count of ways is"),
print(count(n))

# Expected output:
Count of ways is
3
# compute ncr % p | set 1 ( introduction and dynamic programming solution ) | returns ncr % p ; optimization for the cases when r is large compared to n - r ; the array c is going to store last row of pascal triangle at the end . and last entry of last row is ncr . ; top row of pascal triangle ; one by constructs remaining rows of pascal triangle from top to bottom ; fill entries of current row using previous row values ; ncj = ( n - 1 ) cj + ( n - 1 ) c ( j - 1 ) ; 
def nCrModp(n, r, p):
    if (r > n - r):
        r = n - r
    C = [0 for i in range(r + 1)]
    C[0] = 1
    for i in range(1, n + 1):
        for j in range(min(i, r), 0, -1):
            C[j] = (C[j] + C[j - 1]) % p
    return C[r]


n = 10
r = 2
p = 13
print('Value of nCr % p is', nCrModp(n, r, p))

# Expected output:
Value of nCr % p is 6
# count derangements ( permutation such that no element appears in its original position ) |  ; base case ; variables for storing previous values ; using above recursive formula ; return result for n ; 
def countDer(n):
    if n == 1 or n == 2:
        return n - 1
    a = 0
    b = 1
    for i in range(3, n + 1):
        cur = (i - 1) * (a + b)
        a = b
        b = cur
    return b


n = 4
print("Count of Dearrangements is ", countDer(n))

# Expected output:
Count of Dearrangements is  9
# bell numbers ( number of ways to partition a set ) |  ; explicitly fill for j = 0 ; fill for remaining values of j ; 
def bellNumber(n):
    bell = [[0 for i in range(n + 1)]for j in range(n + 1)]
    bell[0][0] = 1
    for i in range(1, n + 1):
        bell[i][0] = bell[i - 1][i - 1]
        for j in range(1, i + 1):
            bell[i][j] = bell[i - 1][j - 1] + bell[i][j - 1]
    return bell[n][0]


for n in range(6):
    print('Bell Number', n, 'is', bellNumber(n))

# Expected output:
Bell Number 0 is 1
Bell Number 1 is 1
Bell Number 2 is 2
Bell Number 3 is 5
Bell Number 4 is 15
Bell Number 5 is 52
# count number of ways to cover a distance | function returns count of ways to cover ' dist ' ; initialize base values . there is one way to cover 0 and 1 distances and two ways to cover 2 distance ; fill the count array in bottom up manner ; 
def printCountDP(dist):
    count = [0] * (dist + 1)
    count[0] = 1
    if dist >= 1:
        count[1] = 1
    if dist >= 2:
        count[2] = 2
    for i in range(3, dist + 1):
        count[i] = (count[i - 1] + count[i - 2] + count[i - 3])
    return count[dist]


dist = 4
print(printCountDP(dist))

# Expected output:
7
# count even length binary sequences with same sum of first and second half bits | returns the count of even length sequences ; calculate sum ( ( ncr ) ^ 2 ) ; compute ncr using nc ( r - 1 ) ncr / nc ( r - 1 ) = ( n + 1 - r ) / r ; ; 
def countSeq(n):
    nCr = 1
    res = 1
    for r in range(1, n + 1):
        nCr = (nCr * (n + 1 - r)) / r
        res += nCr * nCr
    return res


n = 2
print("Count of sequences is"),
print(int(countSeq(n)))

# Expected output:
Count of sequences is
6
# remove minimum elements from either side such that 2 * min becomes more than max |  ; a utility function to find minimum in arr [ l . . h ] ; a utility function to find maximum in arr [ l . . h ] ; returns the minimum number of removals from either end in arr [ l . . h ] so that 2 * min becomes greater than max . ; create a table to store solutions of subproblems ; fill table using above recursive formula . note that the table is filled in diagonal fashion ( similar to http : goo . gl / pqqos ) , from diagonal elements to table [ 0 ] [ n - 1 ] which is the result . ; 
def min1(arr, l, h):
    mn = arr[l]
    for i in range(l + 1, h + 1):
        if (mn > arr[i]):
            mn = arr[i]
    return mn


def max1(arr, l, h):
    mx = arr[l]
    for i in range(l + 1, h + 1):
        if (mx < arr[i]):
            mx = arr[i]
    return mx


def minRemovalsDP(arr, n):
    table = [[0 for x in range(n)]for y in range(n)]
    for gap in range(n):
        i = 0
        for j in range(gap, n):
            mn = min1(arr, i, j)
            mx = max1(arr, i, j)
            table[i][j] = 0 if (2 * mn > mx)else min(table[i]
                                                     [j - 1] + 1, table[i + 1][j] + 1)
            i += 1
    return table[0][n - 1]


arr = [20, 4, 1, 3]
n = len(arr)
print(minRemovalsDP(arr, n))

# Expected output:
3
# count all possible paths from top left to bottom right of a mxn matrix | function to return count of possible paths to reach cell at row number m and column number n from the topmost leftmost cell ( cell at 1 , 1 ) ; if either given row number is first or given column number is first ; if diagonal movements are allowed then the last addition is required . ; 
def numberOfPaths(m, n):
    if (m == 1 or n == 1):
        return 1
    return numberOfPaths(m - 1, n) + numberOfPaths(m, n - 1)


m = 3
n = 3
print(numberOfPaths(m, n))

# Expected output:
6
# count all possible paths from top left to bottom right of a mxn matrix | python3 program to count all possible paths from top left to top bottom using combinatorics ; we have to calculate m + n - 2 c n - 1 here which will be ( m + n - 2 ) ! / ( n - 1 ) ! ( m - 1 ) ! path = 1 ; ; 
def numberOfPaths(m, n):
    path = 1
    for i in range(n, (m + n - 1)):
        path *= i
        path //= (i - n + 1)
    return path


print(numberOfPaths(3, 3))

# Expected output:
6
# longest arithmetic progression | dp | returns length of the longest ap subset in a given set ; create a table and initialize all values as 2. the value of l [ i ] [ j ] stores llap with set [ i ] and set [ j ] as first two elements of ap . only valid entries are the entries where j > i ; initialize the result ; fill entries in last column as 2. there will always be two elements in ap with last number of set as second element in ap ; consider every element as second element of ap ; search for i and k for j ; before changing i , set l [ i ] [ j ] as 2 ; found i and k for j , llap with i and j as first two elements are equal to llap with j and k as first two elements plus 1. l [ j ] [ k ] must have been filled before as we run the loop from right side ; update overall llap , if needed ; change i and k to fill more l [ i ] [ j ] values for current j ; if the loop was stopped due to k becoming more than n - 1 , set the remaining entities in column j as 2 ; 
def lenghtOfLongestAP(set, n):
    if (n <= 2):
        return n
    L = [[0 for x in range(n)]for y in range(n)]
    llap = 2
    for i in range(n):
        L[i][n - 1] = 2
    for j in range(n - 2, 0, -1):
        i = j - 1
        k = j + 1
        while (i >= 0 and k <= n - 1):
            if (set[i] + set[k] < 2 * set[j]):
                k += 1
            elif (set[i] + set[k] > 2 * set[j]):
                L[i][j] = 2
                i -= 1
            else:
                L[i][j] = L[j][k] + 1
                llap = max(llap, L[i][j])
                i -= 1
                k += 1
                while (i >= 0):
                    L[i][j] = 2
                    i -= 1
    return llap


if __name__ == "__main__":
    set1 = [1, 7, 10, 13, 14, 19]
    n1 = len(set1)
    print(lenghtOfLongestAP(set1, n1))
    set2 = [1, 7, 10, 15, 27, 29]
    n2 = len(set2)
    print(lenghtOfLongestAP(set2, n2))
    set3 = [2, 4, 6, 8, 10]
    n3 = len(set3)
    print(lenghtOfLongestAP(set3, n3))

# Expected output:
4
3
5