giulio98/xlcost-single-prompt huggingface dataset:
# minimum number of jumps to reach end | returns minimum number of jumps to reach end ; jumps [ 0 ] will hold the result ; start from the second element , move from right to left and construct the jumps [ ] array where jumps [ i ] represents minimum number of jumps needed to reach arr [ m - 1 ] form arr [ i ] ; if arr [ i ] is 0 then arr [ n - 1 ] can 't be reached from here ; if we can directly reach to the end point from here then jumps [ i ] is 1 ; otherwise , to find out the minimum number of jumps needed to reach arr [ n - 1 ] , check all the points reachable from here and jumps [ ] value for those points ; initialize min value ; following loop checks with all reachavle points and takes the minimum ; handle overflow ; or int_max ; 
def minJumps(arr, n):
    jumps = [0 for i in range(n)]
    for i in range(n - 2, -1, -1):
        if (arr[i] == 0):
            jumps[i] = float('inf')
        elif (arr[i] >= n - i - 1):
            jumps[i] = 1
        else:
            min = float('inf')
            for j in range(i + 1, n):
                if (j <= arr[i] + i):
                    if (min > jumps[j]):
                        min = jumps[j]
            if (min != float('inf')):
                jumps[i] = min + 1
            else:
                jumps[i] = min
    return jumps[0]


arr = [1, 3, 6, 3, 2, 3, 6, 8, 9, 5]
n = len(arr)
print('Minimum number of jumps to reach', 'end is', minJumps(arr, n - 1))

# Expected output:
Minimum number of jumps to reach end is 3
# maximum number of groups that can receive fresh donuts distributed in batches of size k | stores the result of the same recursive calls ; recursive function to find the maximum number of groups that will receive fresh donuts ; store the result for the current state ; store the key and check if it is present in the hashmap ; if already calculated ; if left is 0 ; traverse the array [ ] arr ; decrement arr [ i ] ; update the maximum number of groups ; increment arr [ i ] by 1 ; otherwise , traverse the given array [ ] arr ; decrement arr [ i ] ; update the maximum number of groups ; increment arr [ i ] by 1 ; memoize the result and return it ; function to find the maximum number of groups that will receive fresh donuts ; stores count of remainder by k ; traverse the array [ ] arr ; hashmap to memoize the results ; store the maximum number of groups ; return the answer ; 

memo = {}


def dfs(V, left, K):
    q = 0
    v = [str(int)for int in V]
    key = ",".join(v)
    key += str(left)
    if key in memo:
        return memo[key]
    elif left == 0:
        for i in range(1, K):
            if V[i] > 0:
                V[i] -= 1
                q = max(q, 1 + dfs(V, K - i, K))
                V[i] += 1
    else:
        for i in range(1, K):
            if V[i] > 0:
                V[i] -= 1
                if i <= left:
                    nleft = left - i
                else:
                    nleft = K + left - i
                q = max(q, dfs(V, nleft, K))
                V[i] += 1
    if key in memo:
        memo[key] = q
    else:
        memo[key] = q
    return q


def maxGroups(K, arr):
    V = [0] * (K)
    for x in range(len(arr)):
        V[arr[x] % K] += 1
    memo = {}
    ans = V[0] + dfs(V, 0, K)
    return ans


arr = [1, 2, 3, 4, 5, 6]
K = 3
print(maxGroups(K, arr))

# Expected output:
4
# smallest subarray with sum greater than a given value | returns length of smallest subarray with sum greater than x . if there is no subarray with given sum , then returns n + 1 ; initialize length of smallest subarray as n + 1 ; pick every element as starting point ; initialize sum starting with current start ; if first element itself is greater ; try different ending points for curremt start ; add last element to current sum ; if sum becomes more than x and length of this subarray is smaller than current smallest length , update the smallest length ( or result ) ; 
def smallestSubWithSum(arr, n, x):
    min_len = n + 1
    for start in range(0, n):
        curr_sum = arr[start]
        if (curr_sum > x):
            return 1
        for end in range(start + 1, n):
            curr_sum += arr[end]
            if curr_sum > x and (end - start + 1) < min_len:
                min_len = (end - start + 1)
    return min_len


arr1 = [1, 4, 45, 6, 10, 19]
x = 51
n1 = len(arr1)
res1 = smallestSubWithSum(arr1, n1, x)
if res1 == n1 + 1:
    print("Not possible")
else:
    print(res1)
arr2 = [1, 10, 5, 2, 7]
n2 = len(arr2)
x = 9
res2 = smallestSubWithSum(arr2, n2, x)
if res2 == n2 + 1:
    print("Not possible")
else:
    print(res2)
arr3 = [1, 11, 100, 1, 0, 200, 3, 2, 1, 250]
n3 = len(arr3)
x = 280
res3 = smallestSubWithSum(arr3, n3, x)
if res3 == n3 + 1:
    print("Not possible")
else:
    print(res3)

# Expected output:
3
1
4
# smallest subarray with sum greater than a given value | returns length of smallest subarray with sum greater than x . if there is no subarray with given sum , then returns n + 1 ; initialize current sum and minimum length ; initialize starting and ending indexes ; keep adding array elements while current sum is smaller than or equal to x ; if current sum becomes greater than x . ; update minimum length if needed ; remove starting elements ; 
def smallestSubWithSum(arr, n, x):
    curr_sum = 0
    min_len = n + 1
    start = 0
    end = 0
    while (end < n):
        while (curr_sum <= x and end < n):
            curr_sum += arr[end]
            end += 1
        while (curr_sum > x and start < n):
            if (end - start < min_len):
                min_len = end - start
            curr_sum -= arr[start]
            start += 1
    return min_len


arr1 = [1, 4, 45, 6, 10, 19]
x = 51
n1 = len(arr1)
res1 = smallestSubWithSum(arr1, n1, x)
print("Not possible")if (res1 == n1 + 1)else print(res1)
arr2 = [1, 10, 5, 2, 7]
n2 = len(arr2)
x = 9
res2 = smallestSubWithSum(arr2, n2, x)
print("Not possible")if (res2 == n2 + 1)else print(res2)
arr3 = [1, 11, 100, 1, 0, 200, 3, 2, 1, 250]
n3 = len(arr3)
x = 280
res3 = smallestSubWithSum(arr3, n3, x)
print("Not possible")if (res3 == n3 + 1)else print(res3)

# Expected output:
3
1
4
# count l | function to find the number of arrays of length l such that each element divides the next element ; stores the number of sequences of length i that ends with j ; base case ; iterate over the range [ 0 , l ] ; iterate for all multiples of j ; incrementing dp [ i + 1 ] [ k ] by dp [ i ] [ j ] as the next element is multiple of j ; stores the number of arrays ; add all array of length l that ends with i ; return the resultant count ; 
def numberOfArrays(n, l):
    dp = [[0 for i in range(n + 1)]for i in range(l + 1)]
    dp[0][1] = 1
    for i in range(l):
        for j in range(1, n + 1):
            for k in range(j, n + 1, j):
                dp[i + 1][k] += dp[i][j]
    ans = 0
    for i in range(1, n + 1):
        ans += dp[l][i]
    return ans


if __name__ == '__main__':
    N, L = 2, 4
    print(numberOfArrays(N, L))

# Expected output:
5
# count minimum steps to get the given desired array | returns count of minimum operations to convert a zero array to target array with increment and doubling operations . this function computes count by doing reverse steps , i . e . , convert target to zero array . ; initialize result ( count of minimum moves ) ; keep looping while all elements of target don 't become 0. ; to store count of zeroes in current target array ; to find first odd element ; if odd number found ; if 0 , then increment zero_count ; all numbers are 0 ; all numbers are even ; divide the whole array by 2 and increment result ; make all odd numbers even by subtracting one and increment result . ; 
def countMinOperations(target, n):
    result = 0
    while (True):
        zero_count = 0
        i = 0
        while (i < n):
            if ((target[i] & 1) > 0):
                break
            elif (target[i] == 0):
                zero_count += 1
            i += 1
        if (zero_count == n):
            return result
        if (i == n):
            for j in range(n):
                target[j] = target[j] // 2
            result += 1
        for j in range(i, n):
            if (target[j] & 1):
                target[j] -= 1
                result += 1


arr = [16, 16, 16]
n = len(arr)
print(
    "Minimum number of steps required to",
    "getthegiventargetarrayis",
    countMinOperations(
        arr,
        n))

# Expected output:
Minimum number of steps required to getthegiventargetarrayis 7
# maximize sum of odd | function to find the maximum sum of array elements chosen by player a according to the given criteria ; store the key ; corner case ; check if all the elements can be taken or not ; if the difference is less than or equal to the available chances then pick all numbers ; find the sum of array elements over the range [ start , n ] ; if yes then return that value ; traverse over the range [ 1 , 2 * m ] ; sum of elements for player a ; even chance sum can be obtained by subtracting the odd chances sum - total and picking up the maximum from that ; storing the value in dictionary ; return the maximum sum of odd chances ; 
def recursiveChoosing(arr, start, M, dp):
    key = (start, M)
    if start >= N:
        return 0
    if N - start <= 2 * M:
        return sum(arr[start:])
    psa = 0
    total = sum(arr[start:])
    if key in dp:
        return dp[key]
    for x in range(1, 2 * M + 1):
        psb = recursiveChoosing(arr, start + x, max(x, M), dp)
        psa = max(psa, total - psb)
    dp[key] = psa
    return dp[key]


arr = [2, 7, 9, 4, 4]
N = len(arr)
dp = {}
print(recursiveChoosing(arr, 0, 1, dp))

# Expected output:
10
# number of subsets with product less than k | python3 to find the count subset having product less than k ; declare four vector for dividing array into two halves and storing product value of possible subsets for them ; ignore element greater than k and divide array into 2 halves ; ignore element if greater than k ; generate all subsets for 1 st half ( vect1 ) ; push only in case subset product is less than equal to k ; generate all subsets for 2 nd half ( vect2 ) ; push only in case subset product is less than equal to k ; sort subset2 ; for null subset decrement the value of count ; return count ; 

import bisect


def findSubset(arr, n, k):
    vect1, vect2, subset1, subset2 = [], [], [], []
    for i in range(0, n):
        if arr[i] > k:
            continue
        if i <= n // 2:
            vect1 .append(arr[i])
        else:
            vect2 .append(arr[i])
    for i in range(0, (1 << len(vect1))):
        value = 1
        for j in range(0, len(vect1)):
            if i & (1 << j):
                value *= vect1[j]
        if value <= k:
            subset1 .append(value)
    for i in range(0, (1 << len(vect2))):
        value = 1
        for j in range(0, len(vect2)):
            if i & (1 << j):
                value *= vect2[j]
        if value <= k:
            subset2 .append(value)
    subset2 .sort()
    count = 0
    for i in range(0, len(subset1)):
        count += bisect .bisect(subset2, (k // subset1[i]))
    count -= 1
    return count


if __name__ == "__main__":
    arr = [4, 2, 3, 6, 5]
    n = len(arr)
    k = 25
    print(findSubset(arr, n, k))

# Expected output:
15
# maximum sum subsequence made up of consecutive elements of different parity | function to calculate the maximum sum subsequence with consecutive terms having different parity ; base case ; store the parity of number at the ith position ; if the dp state has already been calculated , return it ; if the array is traversed and no element has been selected yet then select the current element ; if the parity of the current and previously selected element are different , then select the current element ; skip the current element and move to the next element ; return the result ; function to calculate the maximum sum subsequence with consecutive terms having different parity ; initialize the dp [ ] array with - 1 ; initially the prev value is set to say 2 , as the first element can anyways be selected ; 
def maxSum(arr, i, n, prev, is_selected, dp):
    if (i == n):
        return 0
    cur = abs(arr[i]) % 2
    if (dp[i][prev] != -1):
        return dp[i][prev]
    if (i == n - 1 and is_selected == 0):
        dp[i][prev] = arr[i]
        return dp[i][prev]
    if (cur != prev):
        dp[i][prev] = arr[i] + maxSum(arr, i + 1, n, cur, 1, dp)
    dp[i][prev] = max(
        dp[i][prev],
        maxSum(
            arr,
            i + 1,
            n,
            prev,
            is_selected,
            dp))
    return dp[i][prev]


def maxSumUtil(arr, n):
    dp = [[-1 for i in range(3)]for j in range(100)]
    print(maxSum(arr, 0, n, 2, 0, dp))


if __name__ == '__main__':
    arr = [1, 2, 6, 8, -5, 10]
    N = len(arr)
    maxSumUtil(arr, N)

# Expected output:
14
# find minimum number of merge operations to make an array palindrome | returns minimum number of count operations required to make arr [ ] palindrome ; initialize result ; start from two corners ; if corner elements are same , problem reduces arr [ i + 1. . j - 1 ] ; if left element is greater , then we merge right two elements ; need to merge from tail . ; else we merge left two elements ; 
def findMinOps(arr, n):
    ans = 0
    i, j = 0, n - 1
    while i <= j:
        if arr[i] == arr[j]:
            i += 1
            j -= 1
        elif arr[i] > arr[j]:
            j -= 1
            arr[j] += arr[j + 1]
            ans += 1
        else:
            i += 1
            arr[i] += arr[i - 1]
            ans += 1
    return ans


arr = [1, 4, 5, 9, 1]
n = len(arr)
print("Count of minimum operations is " + str(findMinOps(arr, n)))

# Expected output:
Count of minimum operations is 1
# find the smallest positive integer value that cannot be represented as sum of any subset of a given array | returns the smallest number that cannot be represented as sum of subset of elements from set represented by sorted array arr [ 0. . n - 1 ] ; initialize result ; traverse the array and increment ' res ' if arr [ i ] is smaller than or equal to ' res ' . ; 
def findSmallest(arr, n):
    res = 1
    for i in range(0, n):
        if arr[i] <= res:
            res = res + arr[i]
        else:
            break
    return res


arr1 = [1, 3, 4, 5]
n1 = len(arr1)
print(findSmallest(arr1, n1))
arr2 = [1, 2, 6, 10, 11, 15]
n2 = len(arr2)
print(findSmallest(arr2, n2))
arr3 = [1, 1, 1, 1]
n3 = len(arr3)
print(findSmallest(arr3, n3))
arr4 = [1, 1, 3, 4]
n4 = len(arr4)
print(findSmallest(arr4, n4))

# Expected output:
2
4
5
10
# count distinct possible bitwise xor values of subsets of an array | stores the bitwise xor of every possible subset ; function to generate all combinations of subsets and store their bitwise xor in set s ; if the end of the subset is reached ; stores the bitwise xor of the current subset ; iterate comb [ ] to find xor ; insert the bitwise xor of r elements ; otherwise , iterate to generate all possible subsets ; recursive call for next index ; function to find the size of the set having bitwise xor of all the subsets of the given array ; iterate ove the given array ; generate all possible subsets ; print the size of the set ; 

s = set([])


def countXOR(arr, comb, start, end, index, r):
    if (index == r):
        new_xor = 0
        for j in range(r):
            new_xor ^= comb[j]
        s .add(new_xor)
        return
    i = start
    while i <= end and (end - i + 1) >= (r - index):
        comb[index] = arr[i]
        countXOR(arr, comb, i + 1, end, index + 1, r)
        i += 1


def maxSizeSet(arr, N):
    for r in range(2, N + 1):
        comb = [0] * (r + 1)
        countXOR(arr, comb, 0, N - 1, 0, r)
    print(len(s))


arr = [1, 2, 3, 4, 5]
N = len(arr)
maxSizeSet(arr, N)

# Expected output:
8
# size of the subarray with maximum sum | python3 program to print largest contiguous array sum ; function to find the maximum contiguous subarray and print its starting and end index ; 

from sys import maxsize


def maxSubArraySum(a, size):
    max_so_far = -maxsize - 1
    max_ending_here = 0
    start = 0
    end = 0
    s = 0
    for i in range(0, size):
        max_ending_here += a[i]
        if max_so_far < max_ending_here:
            max_so_far = max_ending_here
            start = s
            end = i
        if max_ending_here < 0:
            max_ending_here = 0
            s = i + 1
    return (end - start + 1)


a = [-2, -3, 4, -1, -2, 1, 5, -3]
print(maxSubArraySum(a, len(a)))

# Expected output:
5
# longest subarray of an array which is a subsequence in another array | function to find the length of the longest subarray in arr1 which is a subsequence in arr2 ; length of the array arr1 ; length of the array arr2 ; length of the required longest subarray ; initialize dparray ; traverse array arr1 ; traverse array arr2 ; arr1 [ i - 1 ] contributes to the length of the subarray ; otherwise ; find the maximum value present in dp ; return the result ; 
def LongSubarrSeq(arr1, arr2):
    M = len(arr1)
    N = len(arr2)
    maxL = 0
    DP = [[0 for i in range(N + 1)]for j in range(M + 1)]
    for i in range(1, M + 1):
        for j in range(1, N + 1):
            if (arr1[i - 1] == arr2[j - 1]):
                DP[i][j] = 1 + DP[i - 1][j - 1]
            else:
                DP[i][j] = DP[i][j - 1]
    for i in range(M + 1):
        for j in range(1, N + 1):
            maxL = max(maxL, DP[i][j])
    return maxL


if __name__ == '__main__':
    arr1 = [4, 2, 3, 1, 5, 6]
    arr2 = [3, 1, 4, 6, 5, 2]
    print(LongSubarrSeq(arr1, arr2))

# Expected output:
3
# find minimum difference between any two elements | returns minimum difference between any pair ; initialize difference as infinite ; find the min diff by comparing difference of all possible pairs in given array ; return min diff ; 
def findMinDiff(arr, n):
    diff = 10 ** 20
    for i in range(n - 1):
        for j in range(i + 1, n):
            if abs(arr[i] - arr[j]) < diff:
                diff = abs(arr[i] - arr[j])
    return diff


arr = [1, 5, 3, 19, 18, 25]
n = len(arr)
print("Minimum difference is " + str(findMinDiff(arr, n)))

# Expected output:
Minimum difference is 1
# count possible n | dp array for memoization ; utility function to count n digit numbers with digit i not appearing more than max_digit [ i ] consecutively ; if number with n digits is generated ; create a reference variable ; check if the current state is already computed before ; initialize ans as zero ; check if count of previous digit has reached zero or not ; fill current position only with digits that are unequal to previous digit ; else set the value of count for this new digit accordingly from max_digit [ ] ; function to count n digit numbers with digit i not appearing more than max_digit [ i ] consecutive times ; stores the final count ; print the total count ; 

dp = [[[-1 for i in range(5005)]for i in range(12)]for i in range(12)]


def findCountUtil(N, maxDigit, position, previous, count):
    global dp
    if (position == N):
        return 1
    ans = dp[position][previous][count]
    if (ans != -1):
        return ans
    ans = 0
    for i in range(10):
        if (count == 0 and previous != i):
            ans = (ans + (findCountUtil(N, maxDigit, position + 1,
                   i, maxDigit[i] - 1)) % 1000000007) % 1000000007
        elif (count != 0):
            ans = (ans + (findCountUtil(N, maxDigit, position + 1, i, count - 1 if (previous ==
                   i and position != 0)else maxDigit[i] - 1)) % 1000000007) % 1000000007
    dp[position][previous][count] = ans
    return ans


def findCount(N, maxDigit):
    ans = findCountUtil(N, maxDigit, 0, 0, 1)
    print(ans)


if __name__ == '__main__':
    N = 2
    maxDigit = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
    findCount(N, maxDigit)

# Expected output:
90
# find minimum difference between any two elements | returns minimum difference between any pair ; sort array in non - decreasing order ; initialize difference as infinite ; find the min diff by comparing adjacent pairs in sorted array ; return min diff ; 
def findMinDiff(arr, n):
    arr = sorted(arr)
    diff = 10 ** 20
    for i in range(n - 1):
        if arr[i + 1] - arr[i] < diff:
            diff = arr[i + 1] - arr[i]
    return diff


arr = [1, 5, 3, 19, 18, 25]
n = len(arr)
print("Minimum difference is " + str(findMinDiff(arr, n)))

# Expected output:
Minimum difference is 1
# maximum subarray sum possible after removing at most k array elements | python3 program to implement the above approach ; function to find the maximum subarray sum greater than or equal to 0 by removing k array elements ; base case ; if overlapping subproblems already occurred ; include current element in the subarray ; if k elements already removed from the subarray ; remove current element from the subarray ; utility function to find the maximum subarray sum by removing at most k array elements ; stores maximum subarray sum by removing at most k elements ; calculate maximum element in dp [ ] [ ] ; update res ; if all array elements are negative ; update res ; 

M = 100


def mxSubSum(i, arr, j):
    global dp
    if (i == 0):
        dp[i][j] = max(0, arr[i])
        return dp[i][j]
    if (dp[i][j] != -1):
        return dp[i][j]
    X = max(0, arr[i] + mxSubSum(i - 1, arr, j))
    if (j == 0):
        dp[i][j] = X
        return X
    Y = mxSubSum(i - 1, arr, j - 1)
    dp[i][j] = max(X, Y)
    return dp[i][j]


def MaximumSubarraySum(n, arr, k):
    mxSubSum(n - 1, arr, k)
    res = 0
    for i in range(n):
        for j in range(k + 1):
            res = max(res, dp[i][j])
    if (max(arr) < 0):
        res = max(arr)
    return res


if __name__ == '__main__':
    dp = [[-1 for i in range(100)]for i in range(100)]
    arr = [-2, 1, 3, -2, 4, -7, 20]
    K = 1
    N = len(arr)
    print(MaximumSubarraySum(N, arr, K))

# Expected output:
26
# minimize cost to empty given array where cost of removing an element is its absolute difference with time instant | python3 program for the above approach ; function to find the minimum cost to delete all array elements ; sort the input array ; store the maximum time to delete the array in the worst case ; store the result in cost [ ] [ ] table ; base case ; store the minimum of all cost values of the previous index ; iterate from range [ 1 , n ] using variable i ; update prev ; iterate from range [ 1 , m ] using variable j ; update cost [ i ] [ j ] ; update the prev ; store the minimum cost to delete all elements ; find the minimum of all values of cost [ n ] [ j ] ; print minimum cost ; 

INF = 10000


def minCost(arr, n):
    arr = sorted(arr)
    m = 2 * n
    cost = [[INF for i in range(m + 1)]for i in range(n + 1)]
    cost[0][0] = 0
    prev = 0
    for i in range(1, n + 1):
        prev = cost[i - 1][0]
        for j in range(1, m + 1):
            cost[i][j] = min(cost[i][j], prev + abs(j - arr[i - 1]))
            prev = min(prev, cost[i - 1][j])
    minCost = INF
    for j in range(1, m + 1):
        minCost = min(minCost, cost[n][j])
    print(minCost)


if __name__ == '__main__':
    arr = [4, 2, 4, 4, 5, 2]
    N = len(arr)
    minCost(arr, N)

# Expected output:
4
# longest span with same sum in two binary arrays | returns length of the longest common subarray with same sum ; initialize result ; one by one pick all possible starting points of subarrays ; initialize sums of current subarrays ; conider all points for starting with arr [ i ] ; update sums ; if sums are same and current length is more than maxlen , update maxlen ; 
def longestCommonSum(arr1, arr2, n):
    maxLen = 0
    for i in range(0, n):
        sum1 = 0
        sum2 = 0
        for j in range(i, n):
            sum1 += arr1[j]
            sum2 += arr2[j]
            if (sum1 == sum2):
                len = j - i + 1
                if (len > maxLen):
                    maxLen = len
    return maxLen


arr1 = [0, 1, 0, 1, 1, 1, 1]
arr2 = [1, 1, 1, 1, 1, 0, 1]
n = len(arr1)
print("Length of the longest common span with same "
      "sum is", longestCommonSum(arr1, arr2, n))

# Expected output:
Length of the longest common span with same sum is 6