giulio98/xlcost-single-prompt huggingface dataset:
# number of ways to cut a stick of length n into in even length at most k units long pieces | recursive function to count the total number of ways ; base case if no - solution exist ; condition if a solution exist ; check if already calculated ; initialize counter ; recursive call ; store the answer ; return the answer ; 
def solve(n, k, mod, dp):
    if (n < 0):
        return 0
    if (n == 0):
        return 1
    if (dp[n] != -1):
        return dp[n]
    cnt = 0
    for i in range(2, k + 1, 2):
        cnt = ((cnt % mod + solve(n - i, k, mod, dp) % mod) % mod)
    dp[n] = cnt
    return int(cnt)


if __name__ == '__main__':
    mod = 1e9 + 7
    n = 4
    k = 2
    dp = [-1] * (n + 1)
    ans = solve(n, k, mod, dp)
    print(ans)

# Expected output:
1
# number of ways to select exactly k even numbers from given array | python3 program for the above approach ; function for calculating factorial ; factorial of n defined as : n ! = n * ( n - 1 ) * ... * 1 ; function to find the number of ways to select exactly k even numbers from the given array ; count even numbers ; check if the current number is even ; check if the even numbers to be chosen is greater than n . then , there is no way to pick it . ; the number of ways will be nck ; given array arr [ ] ; 

f = [0] * 12


def fact():
    f[0] = f[1] = 1
    for i in range(2, 11):
        f[i] = i * 1 * f[i - 1]


def solve(arr, n, k):
    fact()
    even = 0
    for i in range(n):
        if (arr[i] % 2 == 0):
            even += 1
    if (k > even):
        print(0)
    else:
        print(f[even] // (f[k] * f[even - k]))


arr = [1, 2, 3, 4]
n = len(arr)
k = 1
solve(arr, n, k)

# Expected output:
2
# count of binary strings of length n having equal count of 0 ' s ▁ and ▁ 1' s | python3 program to implement the above approach ; function to calculate c ( n , r ) % mod dp based approach ; corner case ; stores the last row of pascal 's triangle ; initialize top row of pascal triangle ; construct pascal 's triangle  from top to bottom ; fill current row with the help of previous row ; c ( n , j ) = c ( n - 1 , j ) + c ( n - 1 , j - 1 ) ; 

MOD = 1000000007


def nCrModp(n, r):
    if (n % 2 == 1):
        return -1
    C = [0] * (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]) % MOD
    return C[r]


N = 6
print(nCrModp(N, N // 2))

# Expected output:
20
# convert 1 into x in min steps by multiplying with 2 or 3 or by adding 1 | function to print the minimum number of operations required to convert 1 into x by using three given operations ; initialize a dp array to store min operations for sub - problems ; base condition : no operation required when n is 1 ; multiply the number by 2 ; multiply the number by 3 ; add 1 to the number . ; print the minimum operations ; initialize a list to store the sequence ; backtrack to find the sequence ; if add by 1 ; if multiply by 2 ; if multiply by 3 ; print the sequence of operation ; 
def printMinOperations(N):
    dp = [N] * (N + 1)
    dp[1] = 0
    for i in range(2, N + 1):
        if (i % 2 == 0 and dp[i] > dp[i // 2] + 1):
            dp[i] = dp[i // 2] + 1
        if (i % 3 == 0 and dp[i] > dp[i // 3] + 1):
            dp[i] = dp[i // 3] + 1
        if (dp[i] > dp[i - 1] + 1):
            dp[i] = dp[i - 1] + 1
    print(dp[N], end="")
    seq = []
    while (N > 1):
        seq .append(N)
        if dp[N - 1] == dp[N] - 1:
            N = N - 1
        elif N % 2 == 0 and dp[N // 2] == dp[N] - 1:
            N = N // 2
        else:
            N = N // 3
    seq .append(1)
    for i in reversed(seq):
        print(i, end=" ")


X = 96234
printMinOperations(X)

# Expected output:
141 3 9 10 11 33 99 297 891 2673 8019 16038 16039 48117 96234
# largest subsequence such that all indices and all values are multiples individually | python3 program for the above approach ; function that print maximum length of array ; dp [ ] array to store the maximum length ; find all divisors of i ; if the current value is greater than the divisor 's value ; if current value is greater than the divisor 's value  and s is not equal  to current index ; condition if current value is greater than the divisor 's value ; computing the greatest value ; printing maximum length of array ; 

from math import *


def maxLength(arr, n):
    dp = [1] * n
    for i in range(n - 1, 1, -1):
        for j in range(1, int(sqrt(i)) + 1):
            if (i % j == 0):
                s = i // j
                if (s == j):
                    if (arr[i] > arr[s]):
                        dp[s] = max(dp[i] + 1, dp[s])
                else:
                    if (s != i and arr[i] > arr[s]):
                        dp[s] = max(dp[i] + 1, dp[s])
                    if (arr[i] > arr[j]):
                        dp[j] = max(dp[i] + 1, dp[j])
    Max = 0
    for i in range(1, n):
        if (dp[i] > Max):
            Max = dp[i]
    print(Max)


if __name__ == '__main__':
    arr = [0, 1, 4, 2, 3, 6, 4, 9]
    size = len(arr)
    maxLength(arr, size)

# Expected output:
3
# maximum profit by buying and selling a stock at most twice | set 2 | python3 implmenetation to find maximum possible profit with at most two transactions ; function to find the maximum profit with two transactions on a given list of stock prices ; set initial buying values to int_max as we want to minimize it ; set initial selling values to zero as we want to maximize it ; money lent to buy the stock should be minimum as possible . buy1 tracks the minimum possible stock to buy from 0 to i - 1. ; profit after selling a stock should be maximum as possible . profit1 tracks maximum possible profit we can make from 0 to i - 1. ; now for buying the 2 nd stock , we will integrate profit made from selling the 1 st stock ; profit after selling a 2 stocks should be maximum as possible . profit2 tracks maximum possible profit we can make from 0 to i - 1. ; 

import sys


def maxProfit(price, n):
    buy1, buy2 = sys .maxsize, sys .maxsize
    profit1, profit2 = 0, 0
    for i in range(n):
        buy1 = min(buy1, price[i])
        profit1 = max(profit1, price[i] - buy1)
        buy2 = min(buy2, price[i] - profit1)
        profit2 = max(profit2, price[i] - buy2)
    return profit2


price = [2, 30, 15, 10, 8, 25, 80]
n = len(price)
print("Maximum Profit = ", maxProfit(price, n))

# Expected output:
Maximum Profit =  100
# maximum score of deleting an element from an array based on given condition | python3 implementation to find the maximum score of the deleting a element from an array ; function to find the maximum score of the deleting an element from an array ; creating a map to keep the frequency of numbers ; loop to iterate over the elements of the array ; creating a dp array to keep count of max score at ith element and it will be filled in the bottom up manner ; loop to choose the elements of the array to delete from the array ; 

from collections import defaultdict


def findMaximumScore(a, n):
    freq = defaultdict(int)
    for i in range(n):
        freq[a[i]] += 1
    dp = [0] * (max(a) + 1)
    dp[0] = 0
    dp[1] = freq[1]
    for i in range(2, len(dp)):
        dp[i] = max(dp[i - 1], dp[i - 2] + freq[i] * i)
    return dp[-1]


if __name__ == "__main__":
    n = 3
    a = [1, 2, 3]
    print(findMaximumScore(a, n))

# Expected output:
4
# reverse a subarray to maximize sum of even | function to return maximized sum at even indices ; stores difference with element on the left ; stores difference with element on the right ; compute and store left difference ; for first index ; if previous difference is positive ; otherwise ; for the last index ; otherwise ; for first index ; if the previous difference is positive ; 
def maximizeSum(arr):
    n = len(arr)
    sum = 0
    for i in range(0, n, 2):
        sum += arr[i]
    leftDP = [0] * (n)
    rightDP = [0] * (n)
    c = 0
    for i in range(1, n, 2):
        leftDiff = arr[i] - arr[i - 1]
        if (c - 1 < 0):
            leftDP[i] = leftDiff
        else:
            if (leftDP[i] > 0):
                leftDP[i] = (leftDiff + leftDP[i - 1])
            else:
                leftDP[i] = leftDiff
        rightDiff = 0
        if (i + 1 >= len(arr)):
            rightDiff = 0
        else:
            rightDiff = arr[i] - arr[i + 1]
        if (c - 1 < 0):
            rightDP[i] = rightDiff
        else:
            if (rightDP[i] > 0):
                rightDP[i] = (rightDiff + rightDP[i - 1])
            else:
                rightDP[i] = rightDiff
        c += 1
    maxm = 0
    for i in range(n // 2):
        maxm = max(maxm, max(leftDP[i], rightDP[i]))
    return maxm + sum


if __name__ == '__main__':
    arr = [7, 8, 4, 5, 7, 6, 8, 9, 7, 3]
    ans = maximizeSum(arr)
    print(ans)

# Expected output:
37
# count of all subsequences having adjacent elements with different parity | function to find required subsequences ; initialise the dp [ ] [ ] with 0. ; if odd element is encountered ; considering i - th element will be present in the subsequence ; appending i - th element to all non - empty subsequences ending with even element till ( i - 1 ) th indexes ; considering ith element will not be present in the subsequence ; considering i - th element will be present in the subsequence ; appending i - th element to all non - empty subsequences ending with odd element till ( i - 1 ) th indexes ; considering ith element will not be present in the subsequence ; count of all valid subsequences ; 
def validsubsequences(arr, n):
    dp = [[0 for i in range(2)]for j in range(n + 1)]
    for i in range(1, n + 1):
        if (arr[i - 1] % 2):
            dp[i][1] += 1
            dp[i][1] += dp[i - 1][0]
            dp[i][1] += dp[i - 1][1]
            dp[i][0] += dp[i - 1][0]
        else:
            dp[i][0] += 1
            dp[i][0] += dp[i - 1][1]
            dp[i][0] += dp[i - 1][0]
            dp[i][1] += dp[i - 1][1]
    return dp[n][0] + dp[n][1]


if __name__ == '__main__':
    arr = [5, 6, 9, 7]
    n = len(arr)
    print(validsubsequences(arr, n))

# Expected output:
9
# count of n | function to return count of n - digit numbers with absolute difference of adjacent digits not exceeding k ; for 1 - digit numbers , the count is 10 ; dp [ i ] [ j ] stores the count of i - digit numbers ending with j ; initialize count for 1 - digit numbers ; compute values for count of digits greater than 1 ; find the range of allowed numbers if last digit is j ; perform range update ; prefix sum to find count of of i - digit numbers ending with j ; stores the final answer ; 
def getCount(n, k):
    if n == 1:
        return 10
    dp = [[0 for x in range(11)]for y in range(n + 1)]
    for i in range(1, 10):
        dp[1][i] = 1
    for i in range(2, n + 1):
        for j in range(0, 10):
            l = max(0, j - k)
            r = min(9, j + k)
            dp[i][l] = dp[i][l] + dp[i - 1][j]
            dp[i][r + 1] = dp[i][r + 1] - dp[i - 1][j]
        for j in range(1, 10):
            dp[i][j] = dp[i][j] + dp[i][j - 1]
    count = 0
    for i in range(0, 10):
        count = count + dp[n][i]
    return count


n, k = 2, 1
print(getCount(n, k))

# Expected output:
26
# find if there is a path between two vertices in a directed graph | set 2 | python3 program to find if there is a path between two vertices in a directed graph using dynamic programming ; function to find if there is a path between two vertices in a directed graph ; dp matrix ; set dp [ i ] [ j ] = true if there is edge between i to j ; check for all intermediate vertex ; if vertex is invalid ; if there is a path ; 

X = 6
Z = 2


def existPath(V, edges, u, v):
    mat = [[False for i in range(V)]for j in range(V)]
    for i in range(X):
        mat[edges[i][0]][edges[i][1]] = True
    for k in range(V):
        for i in range(V):
            for j in range(V):
                mat[i][j] = (mat[i][j] or mat[i][k] and mat[k][j])
    if (u >= V or v >= V):
        return False
    if (mat[u][v]):
        return True
    return False


V = 4
edges = [[0, 2], [0, 1], [1, 2], [2, 3], [2, 0], [3, 3]]
u, v = 1, 3
if (existPath(V, edges, u, v)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# maximize the numbers of splits in an array having sum divisible by 3 | python3 program for above approach ; prefix array storing right most index with prefix sums 0 , 1 , 2 ; dp array ; current prefix sum ; calculating the prefix sum modulo 3 ; we dont have a left pointer with prefix sum c ; we cannot consider i as a right pointer of any segment ; we have a left pointer pre [ c ] with prefix sum c ; i is the rightmost index of prefix sum c ; 
def calculate_maximum_splits(arr, N):
    pre = [0, -1, -1]
    dp = [0 for i in range(N)]
    C = 0
    for i in range(N):
        C = C + arr[i]
        C = C % 3
        if pre[C] == -1:
            dp[i] = dp[i - 1]
        else:
            dp[i] = max(dp[i - 1], dp[pre[C]] + 1)
        pre[C] = i
    return dp[N - 1]


arr = [2, 36, 1, 9, 2, 0, 1, 8, 1]
N = len(arr)
print(calculate_maximum_splits(arr, N))

# Expected output:
4
# count of elements having euler 's totient value one less than itself | python3 program for the above approach ; seiev of erotosthenes method to compute all primes ; if current number is marked prime then mark its multiple as non - prime ; function to count the number of element satisfying the condition ; compute the number of primes in count prime array ; print the number of elements satisfying the condition ; 

prime = [0] * (1000001)


def seiveOfEratosthenes():
    for i in range(2, 1000001):
        prime[i] = 1
    i = 2
    while (i * i < 1000001):
        if (prime[i] == 1):
            for j in range(i * i, 1000001, i):
                prime[j] = 0
        i += 1


def CountElements(arr, n, L, R):
    seiveOfEratosthenes()
    countPrime = [0] * (n + 1)
    for i in range(1, n + 1):
        countPrime[i] = (countPrime[i - 1] + prime[arr[i - 1]])
    print(countPrime[R] - countPrime[L - 1])
    return


arr = [2, 4, 5, 8]
N = len(arr)
L = 1
R = 3
CountElements(arr, N, L, R)

# Expected output:
2
# count of elements having odd number of divisors in index range [ l , r ] for q queries | python3 program for the above approach ; function count the number of elements having odd number of divisors ; initialise dp [ ] array ; precomputation ; find the prefix sum ; iterate for each query ; find the answer for each query ; 

import math


def OddDivisorsCount(n, q, a, Query):
    DP = [0 for i in range(n)]
    for i in range(n):
        x = int(math .sqrt(a[i]))
        if (x * x == a[i]):
            DP[i] = 1
    for i in range(1, n):
        DP[i] = DP[i - 1] + DP[i]
    l = 0
    r = 0
    for i in range(q):
        l = Query[i][0]
        r = Query[i][1]
        if (l == 0):
            print(DP[r])
        else:
            print(DP[r] - DP[l - 1])


if __name__ == "__main__":
    N = 5
    Q = 3
    arr = [2, 4, 5, 6, 9]
    Query = [[0, 2], [1, 3], [1, 4]]
    OddDivisorsCount(N, Q, arr, Query)

# Expected output:
1
1
2
# count of subsequences of length 4 in form ( x , x , x + 1 , x + 1 ) | set 2 | function to count the numbers ; array that stores the digits from left to right ; array that stores the digits from right to left ; initially both array store zero ; fill the table for count1 array ; update the count of current character ; fill the table for count2 array ; update the count of cuuent character ; variable that stores the count of the numbers ; traverse input string and get the count of digits from count1 and count2 array such that difference b / w digit is 1 & store it int c1 & c2 . and store it in variable c1 and c2 ; update the ans ; return the final count ; 
def countStableNum(Str, N):
    count1 = [[0 for j in range(10)]for i in range(N)]
    count2 = [[0 for j in range(10)]for i in range(N)]
    for i in range(N):
        for j in range(10):
            count1[i][j], count2[i][j] = 0, 0
    for i in range(N):
        if (i != 0):
            for j in range(10):
                count1[i][j] = (count1[i][j] + count1[i - 1][j])
        count1[i][ord(Str[i]) - ord('0')] += 1
    for i in range(N - 1, -1, -1):
        if (i != N - 1):
            for j in range(10):
                count2[i][j] += count2[i + 1][j]
        count2[i][ord(Str[i]) - ord('0')
                  ] = count2[i][ord(Str[i]) - ord('0')] + 1
    ans = 0
    for i in range(1, N - 1):
        if (Str[i] == '9'):
            continue
        c1 = count1[i - 1][ord(Str[i]) - ord('0')]
        c2 = count2[i + 1][ord(Str[i]) - ord('0') + 1]
        if (c2 == 0):
            continue
        ans = (ans + (c1 * ((c2 * (c2 - 1) // 2))))
    return ans


Str = "224353"
N = len(Str)
print(countStableNum(Str, N))

# Expected output:
1
# maximize occurrences of values between l and r on sequential addition of array elements with modulo h | function that prints the number of times x gets a value between l and r ; base condition ; condition if x can be made equal to j after i additions ; compute value of x after adding arr [ i ] ; compute value of x after adding arr [ i ] - 1 ; update dp as the maximum value ; compute maximum answer from all possible cases ; printing maximum good occurrence of x ; 
def goodInteger(arr, n, h, l, r):
    dp = [[-1 for i in range(h)]for j in range(n + 1)]
    dp[0][0] = 0
    for i in range(n):
        for j in range(h):
            if (dp[i][j] != -1):
                h1 = (j + arr[i]) % h
                h2 = (j + arr[i] - 1) % h
                dp[i + 1][h1] = max(dp[i + 1][h1], dp[i]
                                    [j] + (h1 >= l and h1 <= r))
                dp[i + 1][h2] = max(dp[i + 1][h2], dp[i]
                                    [j] + (h2 >= l and h2 <= r))
    ans = 0
    for i in range(h):
        if (dp[n][i] != -1):
            ans = max(ans, dp[n][i])
    print(ans)


if __name__ == '__main__':
    A = [16, 17, 14, 20, 20, 11, 22]
    H = 24
    L = 21
    R = 23
    size = len(A)
    goodInteger(A, size, H, L, R)

# Expected output:
3
# longest subarray whose elements can be made equal by maximum k increments | function to find maximum possible length of subarray ; stores the sum of elements that needs to be added to the sub array ; stores the index of the current position of subarray ; stores the maximum length of subarray . ; maximum element from each subarray length ; previous index of the current subarray of maximum length ; deque to store the indices of maximum element of each sub array ; for each array element , find the maximum length of required subarray ; traverse the deque and update the index of maximum element . ; if it is first element then update maximum and dp [ ] ; else check if current element exceeds max ; update max and dp [ ] ; update the index of the current maximum length subarray ; while current element being added to dp [ ] array exceeds k ; update index of current position and the previous position ; remove elements from deque and update the maximum element ; update the maximum length of the required subarray . ; 
def validSubArrLength(arr, N, K):
    dp = [0 for i in range(N + 1)]
    pos = 0
    ans = 0
    mx = 0
    pre = 0
    q = []
    for i in range(N):
        while (len(q) and arr[len(q) - 1] < arr[i]):
            q .remove(q[len(q) - 1])
        q .append(i)
        if (i == 0):
            mx = arr[i]
            dp[i] = arr[i]
        elif (mx <= arr[i]):
            dp[i] = dp[i - 1] + arr[i]
            mx = arr[i]
        else:
            dp[i] = dp[i - 1] + arr[i]
        if (pre == 0):
            pos = 0
        else:
            pos = pre - 1
        while ((i - pre + 1) * mx - (dp[i] - dp[pos]) > K and pre < i):
            pos = pre
            pre += 1
            while (len(q) and q[0] < pre and pre < i):
                q .remove(q[0])
                mx = arr[q[0]]
        ans = max(ans, i - pre + 1)
    return ans


if __name__ == '__main__':
    N = 6
    K = 8
    arr = [2, 7, 1, 3, 4, 5]
    print(validSubArrLength(arr, N, K))

# Expected output:
4
# partition of a set into k subsets with equal sum using bitmask and dp | function to check whether k required partitions are possible or not ; return true as the entire array is the answer ; if total number of partitions exceeds size of the array ; if the array sum is not divisible by k ; no such partitions are possible ; required sum of each subset ; initialize dp array with - 1 ; sum of empty subset is zero ; iterate over all subsets / masks ; if current mask is invalid , continue ; iterate over all array elements ; check if the current element can be added to the current subset / mask ; transition ; 
def isKPartitionPossible(arr, N, K):

    if (K == 1):
        return True
    if (N < K):
        return False

    sum = 0
    for i in range(N):
        sum += arr[i]
    if (sum % K != 0):
        return False
    target = sum / K
    dp = [0 for i in range(1 << 15)]
    for i in range((1 << N)):
        dp[i] = -1
    dp[0] = 0
    for mask in range((1 << N)):
        if (dp[mask] == -1):
            continue
        for i in range(N):
            if ((mask & (1 << i) == 0) and
                    dp[mask] + arr[i] <= target):
                dp[mask | (1 << i)] = ((dp[mask] +
                                        arr[i]) %
                                       target)

    if (dp[(1 << N) - 1] == 0):
        return True
    else:
        return False


if __name__ == '__main__':
    arr = [2, 1, 4, 5, 3, 3]
    N = len(arr)
    K = 3
    if (isKPartitionPossible(arr, N, K)):
        print("Partitions into equal sum is possible.")
    else:
        print("Partitions into equal sum is not possible.")

# Expected output:
Partitions into equal sum is possible.
# minimum cost path in a matrix by moving only on value difference of x | python3 implementation to find the minimum number of operations required to move from ( 1 , 1 ) to ( n , m ) ; function to find the minimum operations required to move to bottom - right cell of matrix ; condition to check if the current cell is the bottom - right cell of the matrix ; condition to check if the current cell is out of matrix ; condition to check if the current indices is already computed ; condition to check that the movement with the current value is not possible ; recursive call to compute the number of operation required to compute the value ; function to find the minimum number of operations required to reach the bottom - right cell ; loop to iterate over every possible cell of the matrix ; 

MAX = 1e18
v = [[0, 0]] * (151)
dp = [[-1 for i in range(151)]for i in range(151)]


def min_operation(i, j, val, x):
    if (i == n - 1 and j == m - 1):
        if (val > v[i][j]):
            dp[i][j] = MAX
            return MAX
        else:
            dp[i][j] = v[i][j] - val
            return dp[i][j]
    if (i == n or j == m):
        dp[i][j] = MAX
        return MAX
    if (dp[i][j] != -1):
        return dp[i][j]
    if (val > v[i][j]):
        dp[i][j] = MAX
        return MAX
    tmp = v[i][j] - val
    tmp += min(min_operation(i + 1, j, val + x, x),
               min_operation(i, j + 1, val + x, x))
    dp[i][j] = tmp
    return tmp


def solve(x):
    ans = 10 ** 19
    for i in range(n):
        for j in range(m):
            val = v[i][j] - x * (i + j)
            for ii in range(151):
                for jj in range(151):
                    dp[ii][jj] = -1
            val = min_operation(0, 0, val, x)
            ans = min(ans, val)
    return ans


if __name__ == '__main__':
    n = 2
    m = 2
    x = 3
    v[0] = [15, 153]
    v[1] = [135, 17]
    print(solve(x))

# Expected output:
125