giulio98/xlcost-single-prompt huggingface dataset:
# program for best fit algorithm in memory management | function to allocate memory to blocks as per best fit algorithm ; stores block id of the block allocated to a process ; pick each process and find suitable blocks according to its size ad assign to it ; find the best fit block for current process ; if we could find a block for current process ; allocate block j to p [ i ] process ; reduce available memory in this block . ; 
def bestFit(blockSize, m, processSize, n):
    allocation = [-1] * n
    for i in range(n):
        bestIdx = -1
        for j in range(m):
            if blockSize[j] >= processSize[i]:
                if bestIdx == -1:
                    bestIdx = j
                elif blockSize[bestIdx] > blockSize[j]:
                    bestIdx = j
        if bestIdx != -1:
            allocation[i] = bestIdx
            blockSize[bestIdx] -= processSize[i]
    print("Process No. Process Size Block no.")
    for i in range(n):
        print(i + 1, " ", processSize[i], end=" ")
        if allocation[i] != -1:
            print(allocation[i] + 1)
        else:
            print("Not Allocated")


if __name__ == '__main__':
    blockSize = [100, 500, 200, 300, 600]
    processSize = [212, 417, 112, 426]
    m = len(blockSize)
    n = len(processSize)
    bestFit(blockSize, m, processSize, n)

# Expected output:
Process No. Process Size Block no.
1   212 4
2   417 2
3   112 3
4   426 5
# bin packing problem ( minimize number of used bins ) | returns number of bins required using first fit online algorithm ; initialize result ( count of bins ) ; create an array to store remaining space in bins there can be at most n bins ; place items one by one ; find the first bin that can accommodate weight [ i ] ; initialize minimum space left and index of best bin ; if no bin could accommodate weight [ i ] , create a new bin ; else : assign the item to best bin ; 
def firstFit(weight, n, c):
    res = 0
    bin_rem = [0] * n
    for i in range(n):
        j = 0
        min = c + 1
        bi = 0
        for j in range(res):
            if (bin_rem[j] >= weight[i] and bin_rem[j] - weight[i] < min):
                bi = j
                min = bin_rem[j] - weight[i]
        if (min == c + 1):
            bin_rem[res] = c - weight[i]
            res += 1
            bin_rem[bi] -= weight[i]
    return res


if __name__ == '__main__':
    weight = [2, 5, 4, 7, 1, 3, 8]
    c = 10
    n = len(weight)
    print("Number of bins required in First Fit : ", firstFit(weight, n, c))

# Expected output:
Number of bins required in First Fit :  3
# find minimum time to finish all jobs with given constraints | utility function to get maximum element in job [ 0. . n - 1 ] ; returns true if it is possible to finish jobs [ ] within given time 'time ; cnt is count of current assignees required for jobs ; time assigned to current assignee ; if time assigned to current assignee exceeds max , increment count of assignees . ; else add time of job to current time and move to next job . ; returns true if count is smaller than k ; returns minimum time required to finish given array of jobs k -- > number of assignees t -- > time required by every assignee to finish 1 unit m -- > number of jobs ; set start and end for binary search end provides an upper limit on time ; find the job that takes maximum time ; do binary search for minimum feasible time ; if it is possible to finish jobs in mid time ; ans = min ( ans , mid ) update answer ; 
def getMax(arr, n):
    result = arr[0]
    for i in range(1, n):
        if arr[i] > result:
            result = arr[i]
    return result


def isPossible(time, K, job, n):
    cnt = 1
    curr_time = 0

    i = 0
    while i < n:
        if curr_time + job[i] > time:
            curr_time = 0
            cnt += 1
        else:
            curr_time += job[i]
            i += 1
    return cnt <= K


def findMinTime(K, T, job, n):
    end = 0
    start = 0
    for i in range(n):
        end += job[i]

    ans = end
    job_max = getMax(job, n)
    while start <= end:
        mid = int((start + end) / 2)
        if mid >= job_max and isPossible(mid, K, job, n):
            ans = min(ans, mid)
            end = mid - 1
        else:
            start = mid + 1

    return ans * T


if __name__ == '__main__':
    job = [10, 7, 8, 12, 6, 8]
    n = len(job)
    k = 4
    T = 5
    print(findMinTime(k, T, job, n))

# Expected output:
75
# longest subarray with all even or all odd elements | function to calculate longest substring with odd or even elements ; initializing dp [ ] ; initializing dp [ 0 ] with 1 ; ans will store the final answer ; traversing the array from index 1 to n - 1 ; checking both current and previous element is even or odd ; updating dp [ i ] with dp [ i - 1 ] + 1 ; storing max element to ans ; returning the final answer ; 
def LongestOddEvenSubarray(A, N):
    dp = [0 for i in range(N)]
    dp[0] = 1
    ans = 1
    for i in range(1, N, 1):
        if ((A[i] %
             2 == 0 and A[i - 1] %
             2 == 0) or (A[i] %
                         2 != 0 and A[i - 1] %
                         2 != 0)):
            dp[i] = dp[i - 1] + 1
        else:
            dp[i] = 1
    for i in range(N):
        ans = max(ans, dp[i])
    return ans


if __name__ == '__main__':
    A = [2, 5, 7, 2, 4, 6, 8, 3]
    N = len(A)
    print(LongestOddEvenSubarray(A, N))

# Expected output:
4
# count of subarrays with maximum value as k | function to count the subarrays with maximum not greater than k ; if arr [ i ] > k then arr [ i ] cannot be a part of any subarray . ; count the number of elements where arr [ i ] is not greater than k . ; summation of all possible subarrays in the variable ans . ; function to count the subarrays with maximum value is equal to k ; stores count of subarrays with max <= k - 1. ; stores count of subarrays with max >= k + 1. ; stores count of subarrays with max = k . ; 
def totalSubarrays(arr, n, k):
    ans = 0
    i = 0
    while (i < n):
        if (arr[i] > k):
            i += 1
            continue
        count = 0
        while (i < n and arr[i] <= k):
            i += 1
            count += 1
        ans += ((count * (count + 1)) // 2)
    return ans


def countSubarrays(arr, n, k):
    count1 = totalSubarrays(arr, n, k - 1)
    count2 = totalSubarrays(arr, n, k)
    ans = count2 - count1
    return ans


if __name__ == '__main__':
    n = 4
    k = 3
    arr = [2, 1, 3, 4]
    print(countSubarrays(arr, n, k))

# Expected output:
3
# maximum subsequence sum such that no three are consecutive in o ( 1 ) space | function to calculate the maximum subsequence sum such that no three elements are consecutive ; when n is 1 , answer would be the only element present ; when n is 2 , answer would be sum of elements ; variable to store sum up to i - 3 ; variable to store sum up to i - 2 ; variable to store sum up to i - 1 ; variable to store the final sum of the subsequence ; find the maximum subsequence sum up to index i ; update first , second and third ; return ans ; ; 
def maxSumWO3Consec(A, N):
    if (N == 1):
        return A[0]
    if (N == 2):
        return A[0] + A[1]
    third = A[0]
    second = third + A[1]
    first = max(second, A[1] + A[2])
    sum = max(max(third, second), first)
    for i in range(3, N, 1):
        sum = max(max(first, second + A[i]), third + A[i] + A[i - 1])
        third = second
        second = first
        first = sum
    return sum


if __name__ == '__main__':
    A = [3000, 2000, 1000, 3, 10]
    N = len(A)
    print(maxSumWO3Consec(A, N))

# Expected output:
5013
# minimum number of given operations required to reduce a number to 2 | function to find the minimum number of operations required to reduce n to 2 ; initialize a dp array ; handle the base case ; iterate in the range [ 2 , n ] ; check if i * 5 <= n ; check if i + 3 <= n ; return the result ; 
def findMinOperations(n):
    dp = [0 for i in range(n + 1)]
    for i in range(n + 1):
        dp[i] = 999999
    dp[2] = 0
    for i in range(2, n + 1):
        if (i * 5 <= n):
            dp[i * 5] = min(dp[i * 5], dp[i] + 1)
        if (i + 3 <= n):
            dp[i + 3] = min(dp[i + 3], dp[i] + 1)
    return dp[n]


if __name__ == '__main__':
    n = 28
    m = findMinOperations(n)
    if (m != 9999):
        print(m)
    else:
        print(-1)

# Expected output:
3
# split array into subarrays such that sum of difference between their maximums and minimums is maximum | function to find maximum sum of difference between maximums and minimums in the splitted subarrays ; traverse the array ; stores the maximum and minimum elements upto the i - th index ; traverse the range [ 0 , i ] ; update the minimum ; update the maximum ; update dp [ i ] ; return the maximum sum of difference ; 
def getValue(arr, N):
    dp = [0 for i in range(N)]
    for i in range(1, N):
        minn = arr[i]
        maxx = arr[i]
        j = i
        while (j >= 0):
            minn = min(arr[j], minn)
            maxx = max(arr[j], maxx)
            dp[i] = max(dp[i], maxx - minn + (dp[j - 1]if (j >= 1)else 0))
            j -= 1
    return dp[N - 1]


if __name__ == '__main__':
    arr = [8, 1, 7, 9, 2]
    N = len(arr)
    print(getValue(arr, N))

# Expected output:
14
# maximum score possible by removing substrings made up of single distinct character | function to check if the string s consists of a single distinct character or not ; function to calculate the maximum score possible by removing substrings ; if string is empty ; if length of string is 1 ; store the maximum result ; try to remove all substrings that satisfy the condition and check for resultant string after removal ; store the substring { s [ i ] , . . , s [ j ] } ; check if the substring contains only a single distinct character ; return the maximum score ; 
def isUnique(s):
    return True if len(set(s)) == 1 else False


def maxScore(s, a):
    n = len(s)
    if n == 0:
        return 0
    if n == 1:
        return a[0]
    mx = -1
    for i in range(n):
        for j in range(i, n):
            sub = s[i:j + 1]
            if isUnique(sub):
                mx = max(mx, a[len(sub) - 1] + maxScore(s[:i] + s[j + 1:], a))
    return mx


if __name__ == "__main__":
    s = "011"
    a = [1, 3, 1]
    print(maxScore(s, a))

# Expected output:
4
# maximum score possible by removing substrings made up of single distinct character | initialize a dictionary to store the precomputed results ; function to calculate the maximum score possible by removing substrings ; if s is present in dp [ ] array ; base cases : ; if length of string is 0 ; if length of string is 1 ; put head pointer at start ; initialize the max variable ; generate the substrings using two pointers ; if s [ head ] and s [ tail ] are different ; move head to tail and break ; store the substring ; update the maximum ; move the tail ; store the score ; 

dp = dict()


def maxScore(s, a):
    if s in dp:
        return dp[s]
    n = len(s)
    if n == 0:
        return 0
    if n == 1:
        return a[0]
    head = 0
    mx = -1
    while head < n:
        tail = head
        while tail < n:
            if s[tail] != s[head]:
                head = tail
                break
            sub = s[head:tail + 1]
            mx = max(mx, a[len(sub) - 1] +
                     maxScore(s[:head] + s[tail + 1:], a))
            tail += 1
        if tail == n:
            break
    dp[s] = mx
    return mx


if __name__ == "__main__":
    s = "abb"
    a = [1, 3, 1]
    print(maxScore(s, a))

# Expected output:
4
# count all unique outcomes possible by performing s flips on n coins | dimensions of the dp table ; stores the dp states ; function to recursively count the number of unique outcomes possible by performing s flips on n coins ; base case ; if the count for the current state is not calculated , then calculate it recursively ; otherwise return the already calculated value ; 

size = 100
ans = [[0 for i in range(size)]for j in range(size)]


def numberOfUniqueOutcomes(n, s):
    if (s < n):
        ans[n][s] = 0
    elif (n == 1 or n == s):
        ans[n][s] = 1
    elif (ans[n][s] == 0):
        ans[n][s] = (
            numberOfUniqueOutcomes(
                n -
                1,
                s -
                1) +
            numberOfUniqueOutcomes(
                n -
                1,
                s -
                2))
    return ans[n][s]


N = 5
S = 8
print(numberOfUniqueOutcomes(N, S))

# Expected output:
15
# minimize removals to remove another string as a subsequence of a given string | function to print the minimum number of character removals required to remove x as a subsequence from the string str ; length of the string str ; length of the string x ; stores the dp states ; fill first row of dp [ ] [ ] ; if x [ j ] matches with str [ 0 ] ; if s [ i ] is equal to x [ j ] ; update state after removing str [ i [ ; update state after keeping str [ i ] ; if str [ i ] is not equal to x [ j ] ; print the minimum number of characters removals ; 
def printMinimumRemovals(s, X):
    N = len(s)
    M = len(X)
    dp = [[0 for x in range(M)]for y in range(N)]
    for j in range(M):
        if (s[0] == X[j]):
            dp[0][j] = 1
    for i in range(1, N):
        for j in range(M):
            if (s[i] == X[j]):
                dp[i][j] = dp[i - 1][j] + 1
                if (j != 0):
                    dp[i][j] = min(dp[i][j], dp[i - 1][j - 1])
            else:
                dp[i][j] = dp[i - 1][j]
    print(dp[N - 1][M - 1])


if __name__ == "__main__":
    s = "btagd"
    X = "bad"
    printMinimumRemovals(s, X)

# Expected output:
1
# railway station | tcs codevita 2020 | dp table for memoization ; function to count the number of ways to n - th station ; base cases ; if current state is already evaluated ; count ways in which train 1 can be chosen ; count ways in which train 2 can be chosen ; count ways in which train 3 can be chosen ; store the current state ; return the number of ways ; 

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


def findWays(x):
    if (x < 0):
        return 0
    if (x == 0):
        return 1
    if (x == 1):
        return 2
    if (x == 2):
        return 4
    if (dp[x] != -1):
        return dp[x]
    count = findWays(x - 1)
    count += findWays(x - 2)
    count += findWays(x - 3)
    dp[x] = count
    return dp[x]


if __name__ == '__main__':
    n = 4
    print(findWays(n))

# Expected output:
13
# maximum sum not exceeding k possible for any rectangle of a matrix | python3 program for the above approach ; function to find the maximum possible sum of arectangle which is less than k ; stores the values ( cum_sum - k ) ; insert 0 into the set sumset ; traverse over the rows ; get cumulative sum from [ 0 to i ] ; search for upperbound of ( csum - k ) in the hashmap ; if upper_bound of ( csum - k ) exists , then update max sum ; insert cummulative value in the hashmap ; return the maximum sum which is less than k ; function to find the maximum sum of rectangle such that its sum is no larger than k ; stores the number of rows and columns ; store the required result ; set the left column ; set the right column for the left column set by outer loop ; calculate sum between the current left and right for every row ; stores the sum of rectangle ; update the overall maximum sum ; print the result ; 

from bisect import bisect_left, bisect_right
import sys


def maxSubarraySum(sum, k, row):
    curSum, curMax = 0, -sys .maxsize - 1
    sumSet = {}
    sumSet[0] = 1
    for r in range(row):
        curSum += sum[r]
        arr = list(sumSet .keys())
        it = bisect_left(arr, curSum - k)
        if (it != len(arr)):
            curMax = max(curMax, curSum - it)
        sumSet[curSum] = 1
    return curMax


def maxSumSubmatrix(matrix, k):
    row = len(matrix)
    col = len(matrix[0])
    ret = -sys .maxsize - 1
    for i in range(col):
        sum = [0] * (row)
        for j in range(i, col):
            for r in range(row):
                sum[r] += matrix[r][j]
            curMax = maxSubarraySum(sum, k, row)
            ret = max(ret, curMax)
    print(ret)


if __name__ == '__main__':
    matrix = [[1, 0, 1], [0, -2, 3]]
    K = 2
    maxSumSubmatrix(matrix, K)

# Expected output:
2
# count n | function to count binary strings of length n having substring "11" ; initialize dp [ ] of size n + 1 ; base cases ; stores the first n powers of 2 ; generate ; iterate over the range [ 2 , n ] ; prtotal count of substrings ; 
def binaryStrings(N):
    dp = [0] * (N + 1)
    dp[0] = 0
    dp[1] = 0
    power = [0] * (N + 1)
    power[0] = 1
    for i in range(1, N + 1):
        power[i] = 2 * power[i - 1]
    for i in range(2, N + 1):
        dp[i] = dp[i - 1] + dp[i - 2] + power[i - 2]
    print(dp[N])


if __name__ == '__main__':
    N = 12
    binaryStrings(N)

# Expected output:
3719
# maximum sum submatrix | python3 program for the above approach ; function to find maximum continuous maximum sum in the array ; stores current and maximum sum ; traverse the array v ; add the value of the current element ; update the maximum sum ; return the maximum sum ; function to find the maximum submatrix sum ; store the rows and columns of the matrix ; create an auxiliary matrix traverse the matrix , prefix and initialize it will all 0 s ; calculate prefix sum of all rows of matrix a [ ] [ ] and store in matrix prefix [ ] ; update the prefix [ ] [ ] ; store the maximum submatrix sum ; iterate for starting column ; iterate for last column ; to store current array elements ; traverse every row ; store the sum of the kth row ; update the prefix sum ; push it in a vector ; update the maximum overall sum ; print the answer ; 

import sys


def kadane(v):
    currSum = 0
    maxSum = -sys .maxsize - 1
    for i in range(len(v)):
        currSum += v[i]
        if (currSum > maxSum):
            maxSum = currSum
        if (currSum < 0):
            currSum = 0
    return maxSum


def maxSubmatrixSum(A):
    r = len(A)
    c = len(A[0])
    prefix = [[0 for i in range(c)]for j in range(r)]
    for i in range(r):
        for j in range(c):
            if (j == 0):
                prefix[i][j] = A[i][j]
            else:
                prefix[i][j] = A[i][j] + prefix[i][j - 1]
    maxSum = -sys .maxsize - 1
    for i in range(c):
        for j in range(i, c):
            v = []
            for k in range(r):
                el = 0
                if (i == 0):
                    el = prefix[k][j]
                else:
                    el = prefix[k][j] - prefix[k][i - 1]
                v .append(el)
            maxSum = max(maxSum, kadane(v))
    print(maxSum)


matrix = [[0, -2, -7, 0], [9, 2, -6, 2], [-4, 1, -4, 1], [-1, 8, 0, -2]]
maxSubmatrixSum(matrix)

# Expected output:
15
# minimize cost of painting n houses such that adjacent houses have different colors | function to find the minimum cost of coloring the houses such that no two adjacent houses has the same color ; corner case ; auxiliary 2d dp array ; base case ; if current house is colored with red the take min cost of previous houses colored with ( blue and green ) ; if current house is colored with blue the take min cost of previous houses colored with ( red and green ) ; if current house is colored with green the take min cost of previous houses colored with ( red and blue ) ; print the min cost of the last painted house ; 
def minCost(costs, N):
    if (N == 0):
        return 0
    dp = [[0 for i in range(3)]for j in range(3)]
    dp[0][0] = costs[0][0]
    dp[0][1] = costs[0][1]
    dp[0][2] = costs[0][2]
    for i in range(1, N, 1):
        dp[i][0] = min(dp[i - 1][1], dp[i - 1][2]) + costs[i][0]
        dp[i][1] = min(dp[i - 1][0], dp[i - 1][2]) + costs[i][1]
        dp[i][2] = min(dp[i - 1][0], dp[i - 1][1]) + costs[i][2]
    print(min(dp[N - 1][0], min(dp[N - 1][1], dp[N - 1][2])))


if __name__ == '__main__':
    costs = [[14, 2, 11], [11, 14, 5], [14, 3, 10]]
    N = len(costs)
    minCost(costs, N)

# Expected output:
10
# minimize count of flips required to make sum of the given array equal to 0 | initialize dp [ ] [ ] ; function to find the minimum number of operations to make sum of a [ ] 0 ; initialize answer ; base case ; otherwise , return 0 ; pre - computed subproblem ; recurrence relation for finding the minimum of the sum of subsets ; return the result ; function to find the minimum number of elements required to be flipped to amke sum the array equal to 0 ; find the sum of array ; initialise dp [ ] [ ] with - 1 ; no solution exists ; otherwise ; if sum is odd , no subset is possible ; 

dp = [[-1 for i in range(2001)]for j in range(2001)]


def solve(A, i, sum, N):
    res = 2001
    if (sum < 0 or (i == N and sum != 0)):
        return 2001
    if (sum == 0 or i >= N):
        dp[i][sum] = 0
        return 0
    if (dp[i][sum] != -1):
        return dp[i][sum]
    res = min(solve(A, i + 1, sum - A[i], N) + 1, solve(A, i + 1, sum, N))
    dp[i][sum] = res
    return res


def minOp(A, N):
    sum = 0
    for it in A:
        sum += it
    if (sum % 2 == 0):
        dp = [[-1 for i in range(2001)]for j in range(2001)]
        ans = solve(A, 0, sum // 2, N)
        if (ans < 0 or ans > N):
            print("-1")
        else:
            print(ans)
    else:
        print(-1)


A = [2, 3, 1, 4]
N = len(A)
minOp(A, N)

# Expected output:
2
# count subsequences having average of its elements equal to k | stores the dp states ; function to find the count of subsequences having average k ; base condition ; three loops for three states ; recurrence relation ; stores the sum of dp [ n ] [ j ] [ k * j ] all possible values of j with average k and sum k * j ; iterate over the range [ 1 , n ] ; return the final count ; 

dp = [[[0 for i in range(1001)]for i in range(101)]for i in range(101)]


def countAverage(n, K, arr):
    global dp
    dp[0][0][0] = 1
    for i in range(n):
        for k in range(n):
            for s in range(100):
                dp[i + 1][k + 1][s + arr[i]] += dp[i][k][s]
                dp[i + 1][k][s] += dp[i][k][s]
    cnt = 0
    for j in range(1, n + 1):
        cnt += dp[n][j][K * j]
    return cnt


if __name__ == '__main__':
    arr = [9, 7, 8, 9]
    K = 8
    N = len(arr)
    print(countAverage(N, K, arr))

# Expected output:
5
# count ways to remove pairs from a matrix such that remaining elements can be grouped in vertical or horizontal pairs | function to count ways to remove pairs such that the remaining elements can be arranged in pairs vertically or horizontally ; store the size of matrix ; if n is odd , then no such pair exists ; store the number of required pairs ; initialize an auxiliary matrix and fill it with 0 s ; traverse the matrix v [ ] [ ] ; check if i + j is odd or even ; increment the value dp [ v [ i ] [ j ] - 1 ] [ 0 ] by 1 ; increment the value dp [ v [ i ] [ j ] - 1 ] [ 1 ] by 1 ; iterate in range [ 0 , k - 1 ] using i ; iterate in range [ i + 1 , k - 1 ] using j ; update the ans ; print the answer ; 
def numberofpairs(v, k):
    n = len(v)
    if (n % 2 == 1):
        print(0)
        return
    ans = 0
    dp = [[0 for i in range(2)]for j in range(k)]
    for i in range(k):
        for j in range(2):
            dp[i][j] = 0
    for i in range(n):
        for j in range(n):
            if ((i + j) % 2 == 0):
                dp[v[i][j] - 1][0] += 1
            else:
                dp[v[i][j] - 1][1] += 1
    for i in range(k):
        for j in range(i + 1, k):
            ans += dp[i][0] * dp[j][1]
            ans += dp[i][1] * dp[j][0]
    print(ans)


mat = [[1, 2], [3, 4]]
K = 4
numberofpairs(mat, K)

# Expected output:
4