giulio98/xlcost-single-prompt huggingface dataset:
# largest subarray sum of all connected components in undirected graph | python3 implementation to find largest subarray sum among all connected components ; function to traverse the undirected graph using the depth first traversal ; marking the visited vertex as true ; store the connected chain ; recursive call to the dfs algorithm ; function to return maximum subarray sum of each connected component using kadane 's algorithm ; following loop finds maximum subarray sum based on kadane 's  algorithm ; global maximum subarray sum ; returning the sum ; function to find the maximum subarray sum among all connected components ; initializing boolean array to mark visited vertices ; maxsum stores the maximum subarray sum ; following loop invokes dfs algorithm ; variable to hold temporary length ; variable to hold temporary maximum subarray sum values ; container to store each chain ; dfs algorithm ; variable to hold each chain size ; container to store values of vertices of individual chains ; storing the values of each chain ; function call to find maximum subarray sum of current connection ; conditional to store current maximum subarray sum ; printing global maximum subarray sum ; 

import sys


def depthFirst(v, graph, visited, storeChain):
    visited[v] = True
    storeChain .append(v)
    for i in graph[v]:
        if (visited[i] == False):
            depthFirst(i, graph, visited, storeChain)


def subarraySum(arr, n):
    maxSubarraySum = arr[0]
    currentMax = arr[0]
    for i in range(1, n):
        currentMax = max(arr[i], arr[i] + currentMax)
        maxSubarraySum = max(maxSubarraySum, currentMax)
    return maxSubarraySum


def maxSubarraySum(graph, vertices, values):
    visited = [False for i in range(1001)]
    maxSum = -sys .maxsize
    for i in range(1, vertices + 1):
        if (visited[i] == False):
            sizeChain = 0
            tempSum = 0
            storeChain = []
            depthFirst(i, graph, visited, storeChain)
            sizeChain = len(storeChain)
            chainValues = [0 for i in range(sizeChain + 1)]
            for i in range(sizeChain):
                temp = values[storeChain[i] - 1]
                chainValues[i] = temp
            tempSum = subarraySum(chainValues, sizeChain)
            if (tempSum > maxSum):
                maxSum = tempSum
    print("Maximum subarray sum among all ", end='')
    print("connected components = ", end='')
    print(maxSum)


if __name__ == "__main__":
    graph = [[]for i in range(1001)]
    E = 4
    V = 7
    values = []
    values .append(3)
    values .append(2)
    values .append(4)
    values .append(-2)
    values .append(0)
    values .append(-1)
    values .append(-5)
    graph[1].append(2)
    graph[2].append(1)
    graph[3].append(4)
    graph[4].append(3)
    graph[4].append(5)
    graph[5].append(4)
    graph[6].append(7)
    graph[7].append(6)
    maxSubarraySum(graph, V, values)

# Expected output:
Maximum subarray sum among all connected components = 5
# count of binary strings of length n having atmost m consecutive 1 s or 0 s alternatively exactly k times | list to contain the final result ; function to get the number of desirable binary strings ; if we reach end of string and groups are exhausted , return 1 ; if length is exhausted but groups are still to be made , return 0 ; if length is not exhausted but groups are exhausted , return 0 ; if both are negative just return 0 ; if already calculated , return it ; initialise answer for each state ; loop through every possible m ; 

rows, cols = (1000, 1000)
dp = [[0 for i in range(cols)]for j in range(rows)]


def solve(n, k, m):
    if n == 0 and k == 0:
        return 1
    if n == 0 and k != 0:
        return 0
    if n != 0 and k == 0:
        return 0
    if n < 0 or k < 0:
        return 0
    if dp[n][k]:
        return dp[n][k]
    ans = 0
    for j in range(1, m + 1):
        ans = ans + solve(n - j, k - 1, m)
    dp[n][k] = ans
    return dp[n][k]


N = 7
K = 4
M = 3
print(solve(N, K, M))

# Expected output:
16
# find the length of the largest subset such that all elements are pairwise coprime | dynamic programming table ; function to obtain the mask for any integer ; list of prime numbers till 50 ; iterate through all prime numbers to obtain the mask ; set this prime 's bit on in the mask ; return the mask value ; function to count the number of ways ; check if subproblem has been solved ; excluding current element in the subset ; check if there are no common prime factors then only this element can be included ; calculate the new mask if this element is included ; store and return the answer ; function to find the count of subarray with all digits unique ; 

dp = [[-1] * ((1 << 10) + 5)] * 5000


def getmask(val):
    mask = 0
    prime = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
    for i in range(1, 15):
        if val % prime[i] == 0:
            mask = mask | (1 << i)
    return mask


def calculate(pos, mask, a, n):
    if ((pos == n) or (mask == (1 << n - 1))):
        return 0
    if dp[pos][mask] != -1:
        return dp[pos][mask]
    size = 0
    size = max(size, calculate(pos + 1, mask, a, n))
    if (getmask(a[pos]) & mask) == 0:
        new_mask = (mask | (getmask(a[pos])))
        size = max(size, 1 + calculate(pos + 1, new_mask, a, n))
    dp[pos][mask] = size
    return dp[pos][mask]


def largestSubset(A, n):
    return calculate(0, 0, A, n)


A = [2, 3, 13, 5, 14, 6, 7, 11]
N = len(A)
print(largestSubset(A, N))

# Expected output:
6
# maximum sum such that exactly half of the elements are selected and no two adjacent | function return the maximum sum possible under given condition ; base case ; when i is odd ; when i is even ; maximum of if we pick last element or not ; 
def MaximumSum(a, n):
    dp = [[0 for x in range(2)]for y in range(n + 1)]
    dp[2][1] = a[1]
    dp[2][0] = a[0]
    for i in range(3, n + 1):
        if (i & 1):
            temp = max([dp[i - 3][1], dp[i - 3][0],
                       dp[i - 2][1], dp[i - 2][0]])
            dp[i][1] = a[i - 1] + temp
            dp[i][0] = max([a[i - 2] + dp[i - 2][0],
                            a[i - 2] + dp[i - 3][1],
                            a[i - 2] + dp[i - 3][0],
                            a[i - 3] + dp[i - 3][0]])
        else:
            dp[i][1] = (
                a[i - 1] + max([dp[i - 2][1], dp[i - 2][0], dp[i - 1][0]]))
            dp[i][0] = a[i - 2] + dp[i - 2][0]
    return max(dp[n][1], dp[n][0])


if __name__ == "__main__":
    A = [1, 2, 3, 4, 5, 6]
    N = len(A)
    print(MaximumSum(A, N))

# Expected output:
12
# optimal strategy for the divisor game using dynamic programming | python3 program for implementation of optimal strategy for the divisor game using dynamic programming ; recursive function to find the winner ; check if n = 1 or n = 3 then player b wins ; check if n = 2 then player a wins ; check if current state already visited then return the previously obtained ans ; check if currently it is player a 's turn  then initialise the ans to 0 ; traversing across all the divisors of n which are less than n ; check if current value of i is a divisor of n ; check if it is player a 's turn  then we need at least one true ; else if it is player b 's turn  then we need at least one false ; return the current ans ; 

from math import sqrt


def divisorGame(N, A, dp):
    if (N == 1 or N == 3):
        return False
    if (N == 2):
        return True
    if (dp[N][A] != -1):
        return dp[N][A]
    if (A == 1):
        ans = 0
    else:
        ans = 1
    for i in range(1, int(sqrt(N)) + 1, 1):
        if (N % i == 0):
            if (A):
                ans |= divisorGame(N - i, 0, dp)
            else:
                ans &= divisorGame(N - i, 1, dp)
    dp[N][A] = ans
    return dp[N][A]


if __name__ == '__main__':
    N = 3
    dp = [[-1 for i in range(2)]for j in range(N + 1)]
    if (divisorGame(N, 1, dp)):
        print("Player A wins")
    else:
        print("Player B wins")

# Expected output:
Player B wins
# find the count of mountains in a given matrix | python3 program find the count of mountains in a given matrix ; function to count number of mountains in a given matrix of size n ; form another matrix with one extra layer of border elements . border elements will contain int_min value . ; for border elements , set value as int_min ; for rest elements , just copy it into new matrix ; check for mountains in the modified matrix ; check for all directions ; 

MAX = 100


def countMountains(a, n):
    A = [[0 for i in range(n + 2)]for i in range(n + 2)]
    count = 0
    for i in range(n + 2):
        for j in range(n + 2):
            if ((i == 0) or (j == 0) or (i == n + 1) or (j == n + 1)):
                A[i][j] = float('-inf')
            else:
                A[i][j] = a[i - 1][j - 1]
    for i in range(n + 1):
        for j in range(n + 1):
            if ((A[i][j] > A[i -
                             1][j]) and (A[i][j] > A[i +
                                                     1][j]) and (A[i][j] > A[i][j -
                                                                                1]) and (A[i][j] > A[i][j +
                                                                                                        1]) and (A[i][j] > A[i -
                                                                                                                             1][j -
                                                                                                                                1]) and (A[i][j] > A[i +
                                                                                                                                                     1][j +
                                                                                                                                                        1]) and (A[i][j] > A[i -
                                                                                                                                                                             1][j +
                                                                                                                                                                                1]) and (A[i][j] > A[i +
                                                                                                                                                                                                     1][j -
                                                                                                                                                                                                        1])):
                count = count + 1
    return count


a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
n = 3
print(countMountains(a, n))

# Expected output:
1
# minimum length of the reduced array formed using given operations | python3 implementation to find the minimum length of the array ; function to find the length of minimized array ; creating the required dp tables initialising the dp table by - 1 ; base case ; check if the two subarray can be combined ; initialising dp1 table with max value ; check if the subarray can be reduced to a single element ; minimal partition of [ 1 : j - 1 ] + 1 ; 

import numpy as np


def minimalLength(a, n):
    dp = np .ones((n + 1, n + 1)) * -1
    dp1 = [0] * n
    for size in range(1, n + 1):
        for i in range(n - size + 1):
            j = i + size - 1
            if (i == j):
                dp[i][j] = a[i]
            else:
                for k in range(i, j):
                    if (dp[i][k] != -1 and dp[i][k] == dp[k + 1][j]):
                        dp[i][j] = dp[i][k] + 1
    for i in range(n):
        dp1[i] = int(1e7)
    for i in range(n):
        for j in range(i + 1):
            if (dp[j][i] != -1):
                if (j == 0):
                    dp1[i] = 1
                else:
                    dp1[i] = min(dp1[i], dp1[j - 1] + 1)
    return dp1[n - 1]


if __name__ == "__main__":
    n = 7
    a = [3, 3, 4, 4, 4, 3, 3]
    print(minimalLength(a, n))

# Expected output:
2
# maximum score possible after performing given operations on an array | memoizing by the use of a table ; function to calculate maximum score ; bse case ; if the same state has already been computed ; sum of array in range ( l , r ) ; if the operation is even - numbered the score is decremented ; exploring all paths , and storing maximum value in dp table to avoid further repetitive recursive calls ; function to find the max score ; prefix sum array ; calculating prefix_sum ; initialising the dp table , - 1 represents the subproblem hasn 't been solved yet ; 

dp = [[[-1 for x in range(100)]for y in range(100)]for z in range(100)]


def MaximumScoreDP(l, r, prefix_sum, num):
    if (l > r):
        return 0
    if (dp[l][r][num] != -1):
        return dp[l][r][num]
    current_sum = prefix_sum[r]
    if (l - 1 >= 0):
        current_sum -= prefix_sum[l - 1]
    if (num % 2 == 0):
        current_sum *= -1
    dp[l][r][num] = (current_sum +
                     max(MaximumScoreDP(l +
                                        1, r, prefix_sum, num +
                                        1), MaximumScoreDP(l, r -
                                                           1, prefix_sum, num +
                                                           1)))
    return dp[l][r][num]


def findMaxScore(a, n):
    prefix_sum = [0] * n
    prefix_sum[0] = a[0]
    for i in range(1, n):
        prefix_sum[i] = prefix_sum[i - 1] + a[i]
    global dp
    return MaximumScoreDP(0, n - 1, prefix_sum, 1)


if __name__ == "__main__":
    n = 6
    A = [1, 2, 3, 4, 2, 6]
    print(findMaxScore(A, n))

# Expected output:
13
# count number of binary strings without consecutive 1 â €™ s : set 2 | table to store the solution of every sub problem ; here , pos : keeps track of current position . f1 : is the flag to check if current number is less than n or not . pr : represents the previous digit ; base case ; check if this subproblem has already been solved ; placing 0 at the current position as it does not violate the condition ; here flag will be 1 for the next recursive call ; placing 1 at this position only if the previously inserted number is 0 ; if the number is smaller than n ; if the digit at current position is 1 ; storing the solution to this subproblem ; function to find the number of integers less than or equal to n with no consecutive 1 atms in binary representation ; convert n to binary form ; loop to convert n from decimal to binary ; calling the function ; 

memo = [[[-1 for i in range(2)]for j in range(2)]for k in range(32)]


def dp(pos, fl, pr, bin):
    if (pos == len(bin)):
        return 1
    if (memo[pos][fl][pr] != -1):
        return memo[pos][fl][pr]
    val = 0
    if (bin[pos] == '0'):
        val = val + dp(pos + 1, fl, 0, bin)
    elif (bin[pos] == '1'):
        val = val + dp(pos + 1, 1, 0, bin)
    if (pr == 0):
        if (fl == 1):
            val += dp(pos + 1, fl, 1, bin)
        elif (bin[pos] == '1'):
            val += dp(pos + 1, fl, 1, bin)
    memo[pos][fl][pr] = val
    return val


def findIntegers(num):
    bin = ""
    while (num > 0):
        if (num % 2):
            bin += "1"
        else:
            bin += "0"
        num //= 2
    bin = bin[::-1]
    return dp(0, 0, 0, bin)


if __name__ == "__main__":
    N = 12
    print(findIntegers(N))

# Expected output:
8
# count ways to reach end from start stone with at most k jumps at each step | function which returns total no . of ways to reach nth step from sth steps ; initialize dp array ; initialize ( s - 1 ) th index to 1 ; iterate a loop from s to n ; starting range for counting ranges ; calculate maximum moves to reach ith step ; for nth step return dp [ n - 1 ] ; 
def TotalWays(n, s, k):
    dp = [0] * n
    dp[s - 1] = 1
    for i in range(s, n):
        idx = max(s - 1, i - k)
        for j in range(idx, i):
            dp[i] += dp[j]
    return dp[n - 1]


if __name__ == "__main__":
    n = 5
    k = 2
    s = 2
    print("Total Ways = ", TotalWays(n, s, k))

# Expected output:
Total Ways =  3
# maximum subsequence sum with adjacent elements having atleast k difference in index | function to find the maximum sum subsequence such that two adjacent element have atleast difference of k in their indices ; dp array to store the maximum sum obtained till now ; either select the first element or nothing ; either select the ( i - 1 ) element or let the previous best answer be the current best answer ; either select the best sum till previous_index or select the current element + best_sum till index - k ; 
def max_sum(arr, n, k):
    dp = [0] * n
    dp[0] = max(0, arr[0])
    i = 1
    while (i < k):
        dp[i] = max(dp[i - 1], arr[i])
        i += 1
    i = k
    while (i < n):
        dp[i] = max(dp[i - 1], arr[i] + dp[i - k])
        i += 1
    return dp[n - 1]


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

# Expected output:
4
# number of binary strings such that there is no substring of length â ‰¥ 3 | python3 implementation of the approach ; function to return the count of all possible binary strings ; base cases ; dp [ i ] [ j ] is the number of possible strings such that '1' just appeared consecutively j times upto ith index ; taking previously calculated value ; taking all the possible cases that can appear at the nth position ; 

MOD = 1000000007


def countStr(N):
    dp = [[0 for i in range(3)]for i in range(N + 1)]
    dp[1][0] = 1
    dp[1][1] = 1
    dp[1][2] = 0
    for i in range(2, N + 1):
        dp[i][0] = (dp[i - 1][0] + dp[i - 1][1] + dp[i - 1][2]) % MOD
        dp[i][1] = dp[i - 1][0] % MOD
        dp[i][2] = dp[i - 1][1] % MOD
    ans = (dp[N][0] + dp[N][1] + dp[N][2]) % MOD
    return ans


if __name__ == '__main__':
    N = 8
    print(countStr(N))

# Expected output:
149
# count number of ways to get odd sum | count the ways to sum up with odd by choosing one element form each pair ; initialize two array with 0 ; if element is even ; store count of even number in i 'th pair ; if the element is odd ; store count of odd number in i 'th pair ; initial state of dp array ; dp [ i ] [ 0 ] = total number of ways to get even sum upto i 'th pair ; dp [ i ] [ 1 ] = total number of ways to odd even sum upto i 'th pair ; dp [ n - 1 ] [ 1 ] = total number of ways to get odd sum upto n 'th pair ; 
def CountOfOddSum(a, n):
    dp = [[0 for i in range(2)]for i in range(n)]
    cnt = [[0 for i in range(2)]for i in range(n)]
    for i in range(n):
        for j in range(2):
            if (a[i][j] % 2 == 0):
                cnt[i][0] += 1
            else:
                cnt[i][1] += 1
    dp[0][0] = cnt[0][0]
    dp[0][1] = cnt[0][1]
    for i in range(1, n):
        dp[i][0] = (dp[i - 1][0] * cnt[i][0] + dp[i - 1][1] * cnt[i][1])
        dp[i][1] = (dp[i - 1][0] * cnt[i][1] + dp[i - 1][1] * cnt[i][0])
    return dp[n - 1][1]


a = [[1, 2], [3, 6]]
n = len(a)
ans = CountOfOddSum(a, n)
print(ans)

# Expected output:
2
# longest consecuetive subsequence when only one insert operation is allowed | function to return the length of longest consecuetive subsequence after inserting an element ; variable to find maximum value of the array ; calculating maximum value of the array ; declaring the dp table ; variable to store the maximum length ; iterating for every value present in the array ; recurrence for dp [ val ] [ 0 ] ; no value can be inserted before 1 , hence the element value should be greater than 1 for this recurrance relation ; recurrence for dp [ val ] [ 1 ] ; maximum length of consecutive sequence ending at 1 is equal to 1 ; update the ans variable with the new maximum length possible ; return the ans ; 
def LongestConsSeq(arr, N):
    maxval = 1
    for i in range(N):
        maxval = max(maxval, arr[i])
    dp = [[0 for i in range(2)]for i in range(maxval + 1)]
    ans = 1
    for i in range(N):
        dp[arr[i]][0] = 1 + dp[arr[i] - 1][0]
        if (arr[i] >= 2):
            dp[arr[i]][1] = max(1 + dp[arr[i] - 1][1], 2 + dp[arr[i] - 2][0])
        else:
            dp[arr[i]][1] = 1
        ans = max(ans, dp[arr[i]][1])
    return ans


arr = [2, 1, 4, 5]
N = len(arr)
print(LongestConsSeq(arr, N))

# Expected output:
4
# stepping numbers | this function checks if an integer n is a stepping number ; initalize prevdigit with - 1 ; iterate through all digits of n and compare difference between value of previous and current digits ; get current digit ; single digit is consider as a stepping number ; check if absolute difference between prev digit and current digit is 1 ; a brute force approach based function to find all stepping numbers . ; iterate through all the numbers from [ n , m ] and check if its a stepping number . ; 
def isStepNum(n):
    prevDigit = -1
    while (n):
        curDigit = n % 10
        if (prevDigit == -1):
            prevDigit = curDigit
        else:
            if (abs(prevDigit - curDigit) != 1):
                return False
        prevDigit = curDigit
        n //= 10
    return True


def displaySteppingNumbers(n, m):
    for i in range(n, m + 1):
        if (isStepNum(i)):
            print(i, end=" ")


if __name__ == '__main__':
    n, m = 0, 21
    displaySteppingNumbers(n, m)

# Expected output:
0 1 2 3 4 5 6 7 8 9 10 12 21
# count numbers in given range such that sum of even digits is greater than sum of odd digits | python code to count number in the range having the sum of even digits greater than the sum of odd digits ; base case ; check if condition satisfied or not ; if this result is already computed simply return it ; maximum limit upto which we can place digit . if tight is 0 , means number has already become smaller so we can place any digit , otherwise num [ index ] ; if current digit is odd ; if current digit is even ; function to convert n into its digit vector and uses memo ( ) function to return the required count ; initialize dp ; 
def memo(index, evenSum, oddSum, tight):
    if index == len(v):
        if evenSum > oddSum:
            return 1
        else:
            return 0
    if dp[index][evenSum][oddSum][tight] != -1:
        return dp[index][evenSum][oddSum][tight]
    limit = v[index]if tight else 9
    ans = 0
    for d in range(limit + 1):
        currTight = 0
        if d == v[index]:
            currTight = tight
        if d % 2 != 0:
            ans += memo(index + 1, evenSum, oddSum + d, currTight)
        else:
            ans += memo(index + 1, evenSum + d, oddSum, currTight)
    dp[index][evenSum][oddSum][tight] = ans
    return ans


def countNum(n):
    global dp, v
    v .clear()
    num = []
    while n:
        v .append(n % 10)
        n //= 10
    v .reverse()
    dp = [[[[-1, -1]for i in range(180)]for j in range(180)]for k in range(18)]
    return memo(0, 0, 0, 1)


if __name__ == "__main__":
    dp = []
    v = []
    L = 2
    R = 10
    print(countNum(R) - countNum(L - 1))

# Expected output:
4
# maximum sub | function to return the maximum sum of the sub - sequence such that two consecutive elements have a difference of at least 3 in their indices in the given array ; if there is a single element in the array ; either select it or don 't ; if there are two elements ; either select the first element or don 't ; either select the first or the second element or don 't select any element ; either select the first element or don 't ; either select the first or the second element or don 't select any element ; either select first , second , third or nothing ; for the rest of the elements ; either select the best sum till previous_index or select the current element + best_sum till index - 3 ; 
def max_sum(a, n):
    dp = [0] * n
    if (n == 1):
        dp[0] = max(0, a[0])
    elif (n == 2):
        dp[0] = max(0, a[0])
        dp[1] = max(a[1], dp[0])
    elif (n >= 3):
        dp[0] = max(0, a[0])
        dp[1] = max(a[1], max(0, a[0]))
        dp[2] = max(a[2], max(a[1], max(0, a[0])))
        i = 3
        while (i < n):
            dp[i] = max(dp[i - 1], a[i] + dp[i - 3])
            i += 1
    return dp[n - 1]


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

# Expected output:
5