giulio98/xlcost-single-prompt huggingface dataset:
# maximum cost path in an undirected graph such that no edge is visited twice in a row | python3 program for the above approach ; to store the resulting sum of the cost ; to store largest cost leaf vertex ; dfs traversal to find the update the maximum cost of from any node to leaf ; mark vertex as visited ; store vertex initial cost ; initially assuming edge not to be traversed ; back edge found so , edge can be part of traversal ; new vertex is found ; bitwise and the current check with the returned check by the previous dfs call ; adds parent and its children cost ; updates total cost of parent including child nodes ; edge is part of the cycle ; add cost of vertex to the answer ; updates the largest cost leaf vertex ; function to find the maximum cost from source vertex such that no two edges is traversed twice ; dfs call ; print the maximum cost ; 

N = 100000
canTake = 0
best = 0
dp = [0 for i in range(N)]
vis = [0 for i in range(N)]


def dfs(g, cost, u, pre):
    global canTake, best
    vis[u] = True
    dp[u] = cost[u]
    check = 1
    cur = cost[u]
    for x in g[u]:
        if (vis[x] and x != pre):
            check = 0
        elif (not vis[x]):
            check &= dfs(g, cost, x, u)
            cur = max(cur, cost[u] + dp[x])
    dp[u] = cur
    if (not check):
        canTake += cost[u]
    else:
        best = max(best, dp[u])
    return check


def FindMaxCost(g, cost, source):
    dfs(g, cost, source, -1)
    print(canTake + best)


if __name__ == '__main__':
    n = 5
    m = 5
    cost = [2, 2, 8, 6, 9]
    g = [[]for i in range(n)]
    g[0].append(1)
    g[1].append(0)
    g[0].append(2)
    g[2].append(0)
    g[0].append(3)
    g[3].append(0)
    g[1].append(2)
    g[2].append(1)
    g[1].append(4)
    g[4].append(1)
    source = 1
    FindMaxCost(g, cost, source)

# Expected output:
21
# reverse a subarray of the given array to minimize the sum of elements at even position | function that will give the max negative value ; check for count greater than 0 as we require only negative solution ; function to print the minimum sum ; taking sum of only even index elements ; initialize two vectors v1 , v2 ; v1 will keep account for change if 1 th index element goes to 0 ; v2 will keep account for change if 1 th index element goes to 2 ; get the max negative value ; 
def after_rev(v):
    mini = 0
    count = 0
    for i in range(len(v)):
        count += v[i]
        if (count > 0):
            count = 0
        if (mini > count):
            mini = count
    return mini


def print_f(arr):
    sum = 0
    for i in range(0, len(arr), 2):
        sum += arr[i]
    v1, v2 = [], []
    i = 1
    while i + 1 < len(arr):
        v1 .append(arr[i + 1] - arr[i])
        i += 2
    i = 1
    while i + 1 < len(arr):
        v2 .append(arr[i] - arr[i + 1])
        i += 2
    change = min(after_rev(v1), after_rev(v2))
    if (change < 0):
        sum += change
    print(sum)


if __name__ == '__main__':
    arr = [0, 1, 4, 3]
    print_f(arr)

# Expected output:
1
# smallest number to be added in first array modulo m to make frequencies of both arrays equal | python3 program for the above approach ; utility function to find the answer ; stores the frequencies of array elements ; stores the possible values of x ; generate possible positive values of x ; initialize answer to max value ; flag to check if the current element of the set can be considered ; if the frequency of an element in a [ ] is not equal to that in b [ ] after the operation ; current set element cannot be considered ; update minimum value of x ; 

import sys
from collections import defaultdict


def moduloEquality(A, B, n, m):
    mapA = defaultdict(int)
    mapB = defaultdict(int)
    for i in range(n):
        mapA[A[i]] += 1
        mapB[B[i]] += 1
    possibleValues = set()
    FirstElement = B[0]
    for i in range(n):
        cur = A[i]
        if cur > FirstElement:
            possibleValues .add(m - cur + FirstElement)
        else:
            possibleValues .add(FirstElement - cur)
    ans = sys .maxsize
    for it in possibleValues:
        possible = True
        for it2 in mapA:
            if (mapA[it2] != mapB[(it2 + it) % m]):
                possible = False
                break
        if (possible):
            ans = min(ans, it)
    return ans


if __name__ == "__main__":
    n = 4
    m = 3
    A = [0, 0, 2, 1]
    B = [2, 0, 1, 1]
    print(moduloEquality(A, B, n, m))

# Expected output:
1
# count all indices of cyclic regular parenthesis | function to find all indices which cyclic shift leads to get balanced parenthesis ; create auxiliary array ; finding prefix sum and minimum element ; update the minimum element ; check if count of ' ( ' and ' ) ' are equal ; find count of minimum element ; find the frequency of mn ; return the count ; 
def countCyclicShifts(S, n):
    aux = [0 for i in range(n)]
    for i in range(0, n):
        if (S[i] == '('):
            aux[i] = 1
        else:
            aux[i] = -1
    mn = aux[0]
    for i in range(1, n):
        aux[i] += aux[i - 1]
        mn = min(mn, aux[i])
    if (aux[n - 1] != 0):
        return 0
    count = 0
    for i in range(0, n):
        if (aux[i] == mn):
            count += 1
    return count


S = ")()("
N = len(S)
print(countCyclicShifts(S, N))

# Expected output:
2
# maximize profit by trading stocks based on given rate per day | function to find the maximum profit ; start from the last day ; traverse and keep adding the profit until a day with price of stock higher than currentday is obtained ; set this day as currentday with maximum cost of stock currently ; return the profit ; 
def maxProfit(prices, n):
    profit = 0
    currentDay = n - 1
    while (currentDay > 0):
        day = currentDay - 1
        while (day >= 0 and (prices[currentDay] > prices[day])):
            profit += (prices[currentDay] - prices[day])
            day -= 1
        currentDay = day
    return profit


prices = [2, 3, 5]
N = len(prices)
print(maxProfit(prices, N))

# Expected output:
5
# check given string is oddly palindrome or not | set 2 | function to check if string formed by odd indices is palindromic or not ; check if length of oddstring odd , to consider edge case ; push odd index character of first half of str in stack ; middle element of odd length palindromic string is not compared ; if stack is empty then return true ; 
def isOddStringPalindrome(str, n):
    oddStringSize = n // 2
    lengthOdd = True if (oddStringSize % 2 == 1)else False
    s = []
    i = 1
    c = 0
    while (i < n and c < oddStringSize // 2):
        s .append(str[i])
        i += 2
        c += 1
    if (lengthOdd):
        i = i + 2
    while (i < n and len(s) > 0):
        if (s[len(s) - 1] == str[i]):
            s .pop()
        else:
            break
        i = i + 2
    if (len(s) == 0):
        return True
    return False


if __name__ == "__main__":
    N = 10
    s = "aeafacafae"
    if (isOddStringPalindrome(s, N)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# check given string is oddly palindrome or not | set 2 | functions checks if characters at odd index of the string forms palindrome or not ; initialise two pointers ; iterate till left <= right ; if there is a mismatch occurs then return false ; increment and decrement the left and right pointer by 2 ; 
def isOddStringPalindrome(Str, n):
    left, right = 0, 0
    if (n % 2 == 0):
        left = 1
        right = n - 1
    else:
        left = 1
        right = n - 2
    while (left < n and right >= 0 and left < right):
        if (Str[left] != Str[right]):
            return False
        left += 2
        right -= 2
    return True


if __name__ == '__main__':
    n = 10
    Str = "aeafacafae"
    if (isOddStringPalindrome(Str, n)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# remove minimum characters from string to split it into three substrings under given constraints | python 3 program for the above approach ; function that counts minimum character that must be removed ; length of string ; create prefix array ; initialize first position ; fill prefix array ; initialise maxi ; check all the possibilities by putting i and j at different position & find maximum among them ; print the characters to be removed ; 

import sys


def min_remove(st):
    N = len(st)
    prefix_a = [0] * (N + 1)
    prefix_b = [0] * (N + 1)
    prefix_c = [0] * (N + 1)
    prefix_a[0] = 0
    prefix_b[0] = 0
    prefix_c[0] = 0
    for i in range(1, N + 1):
        if (st[i - 1] == 'a'):
            prefix_a[i] = (prefix_a[i - 1] + 1)
        else:
            prefix_a[i] = prefix_a[i - 1]
        if (st[i - 1] == 'b'):
            prefix_b[i] = (prefix_b[i - 1] + 1)
        else:
            prefix_b[i] = prefix_b[i - 1]
        if (st[i - 1] == 'c'):
            prefix_c[i] = (prefix_c[i - 1] + 1)
        else:
            prefix_c[i] = prefix_c[i - 1]
    maxi = -sys .maxsize - 1
    for i in range(N + 1):
        for j in range(i, N + 1):
            maxi = max(
                maxi, (prefix_a[i] + (prefix_b[j] - prefix_b[i]) + (prefix_c[N] - prefix_c[j])))
    print((N - maxi))


if __name__ == "__main__":
    st = "aaaabaaxccac"
    min_remove(st)

# Expected output:
3
# create an array of size n with sum s such that no subarray exists with sum s or s | function to create an array with n elements with sum as s such that the given conditions satisfy ; check if the solution exists ; print the array as print ( n - 1 ) elements of array as 2 ; print the last element of the array ; print the value of k ; if solution doesnot exists ; 
def createArray(n, s):
    if (2 * n <= s):
        for i in range(n - 1):
            print(2, end=" ")
            s -= 2
        print(s)
        print(1)
    else:
        print('-1')


N = 1
S = 4
createArray(N, S)

# Expected output:
4
1
# maximize partitions such that no two substrings have any common character | function to calculate and return the maximum number of partitions ; r : stores the maximum number of partitions k : stores the ending index of the partition ; stores the last index of every unique character of the string ; traverse the and store the last index of every character ; store the last index of the first character from map ; update k to find the end of partition ; otherwise , the end of partition is found ; increment r ; update k for the next partition ; add the last partition ; 
def maximum_partition(strr):
    i = 0
    j = 0
    k = 0
    c = 0
    r = 0
    m = {}
    for i in range(len(strr) - 1, -1, -1):
        if (strr[i]not in m):
            m[strr[i]] = i
    i = 0
    k = m[strr[i]]
    for i in range(len(strr)):
        if (i <= k):
            c = c + 1
            k = max(k, m[strr[i]])
        else:
            r = r + 1
            c = 1
            k = max(k, m[strr[i]])
    if (c != 0):
        r = r + 1
    return r


if __name__ == '__main__':
    strr = "ababcbacadefegdehijhklij"
    print(maximum_partition(strr))

# Expected output:
3
# minimize steps required to move all 1 's in a matrix to a given index | function to calculate and return the minimum number of steps required to move all 1 s to ( x , y ) ; iterate the given matrix ; update the answer with minimum moves required for the given element to reach the given index ; return the number of steps ; given matrix ; 
def findAns(mat, x, y, n, m):
    ans = 0
    for i in range(n):
        for j in range(m):
            if (mat[i][j] == 1):
                ans += (abs(x - i) + abs(y - j))
    return ans


mat = [[1, 0, 0, 0], [0, 1, 0, 1], [1, 0, 1, 1]]
x = 0
y = 2
print(findAns(mat, x, y, len(mat), len(mat[0])))

# Expected output:
15
# count of all possible reverse bitonic subarrays | function that counts all the reverse bitonic subarray in arr [ ] ; to store the count of reverse bitonic subarray ; iterate the array and select the starting element ; iterate for selecting the ending element for subarray ; subarray arr [ i to j ] ; for 1 length , increment the count and continue ; for decreasing subarray ; check if only decreasing ; for increasing subarray ; print the total count of subarrays ; 
def countReversebitonic(arr, n):
    c = 0
    for i in range(n):
        for j in range(i, n):
            temp = arr[i]
            f = 0
            if (j == i):
                c += 1
                continue
            k = i + 1
            while (k <= j and temp > arr[k]):
                temp = arr[k]
                k += 1
            if (k > j):
                c += 1
                f = 2
            while (k <= j and temp < arr[k] and f != 2):
                temp = arr[k]
                k += 1
            if (k > j and f != 2):
                c += 1
                f = 0
    print(c)


arr = [2, 3, 1, 4]
countReversebitonic(arr, len(arr))

# Expected output:
8
# longest increasing sequence by the boundary elements of an array | python3 program to print the longest increasing subsequence from the boundary elements of an array ; function to return the length of longest increasing subsequence ; set pointers at both ends ; stores the recent value added to the subsequence ; stores the length of the subsequence ; check if both elements can be added to the subsequence ; check if the element on the left can be added to the subsequence only ; check if the element on the right can be added to the subsequence only ; if none of the values can be added to the subsequence ; 

import sys


def longestSequence(n, arr):
    l = 0
    r = n - 1
    prev = -sys .maxsize - 1
    ans = 0
    while (l <= r):
        if (arr[l] > prev and arr[r] > prev):
            if (arr[l] < arr[r]):
                ans += 1
                prev = arr[l]
                l += 1
            else:
                ans += 1
                prev = arr[r]
                r -= 1
        elif (arr[l] > prev):
            ans += 1
            prev = arr[l]
            l += 1
        elif (arr[r] > prev):
            ans += 1
            prev = arr[r]
            r -= 1
        else:
            break
    return ans


arr = [3, 5, 1, 4, 2]
n = len(arr)
print(longestSequence(n, arr))

# Expected output:
4
# total number of cells covered in a matrix after d days | function to return the total infected cells after d days ; top extension ; bottom extension ; left extension ; right extension ; calculating the cells in each quadrilateral ; sum all of them to get total cells in each quadrilateral ; add the singleblocks along the lines of top , down , left , right ; return the ans ; 
def solve(n, m, x, y, d):
    top = min(d, x - 1)
    down = min(d, n - x)
    left = min(d, y - 1)
    right = min(d, m - y)
    quad1 = top * left
    quad2 = left * down
    quad3 = down * right
    quad4 = right * top
    totalsq = (quad1 + quad2 + quad3 + quad4)
    singleBlocks = (top + down + left + right + 1)
    return totalsq + singleBlocks


if __name__ == '__main__':
    n = 10
    m = 10
    x = 7
    y = 8
    d = 4
    d -= 1
    print(solve(n, m, x, y, d))

# Expected output:
42
# smallest subsequence with sum of absolute difference of consecutive elements maximized | function to print the smallest subsequence and its sum ; final subsequence ; first element is a default endpoint ; iterating through the array ; check for monotonically increasing endpoint ; check for monotonically decreasing endpoint ; last element is a default endpoint ; length of final subsequence ; print the subsequence ; 
def getSubsequence(arr, n):
    req = []
    req .append(arr[0])
    for i in range(1, n - 1):
        if (arr[i] > arr[i + 1] and arr[i] > arr[i - 1]):
            req .append(arr[i])
        elif (arr[i] < arr[i + 1] and arr[i] < arr[i - 1]):
            req .append(arr[i])
    req .append(arr[n - 1])
    print(len(req))
    for x in req:
        print(x, end=' ')


if __name__ == '__main__':
    arr = [1, 2, 5, 3, 6, 7, 4]
    n = len(arr)
    getSubsequence(arr, n)

# Expected output:
5
1 5 3 7 4
# minimum steps to convert all paths in matrix from top left to bottom right as palindromic paths | python3 implementation to find the minimum number of changes required such that every path from top left to the bottom right are palindromic paths ; function to find the minimum number of the changes required for the every path to be palindromic ; count variable for maintaining total changes . ; left and right variables for keeping distance values from cell ( 0 , 0 ) and ( n - 1 , m - 1 ) respectively . ; iterating over the matrix ; finding minimum number of changes required . ; minimum no . of changes will be the the minimum no . of different values and we will assume to make them equals to value with maximum frequency element ; moving ahead with greater distance ; 

M = 3
N = 3


def minchanges(mat):
    count = 0
    left = 0
    right = N + M - 2
    while (left < right):
        mp = {}
        totalsize = 0
        for i in range(N):
            for j in range(M):
                if (i + j == left):
                    mp[mat[i][j]] = mp .get(mat[i][j], 0) + 1
                    totalsize += 1
                elif (i + j == right):
                    mp[mat[i][j]] = mp .get(mat[i][j], 0) + 1
                    totalsize += 1
        changes = 0
        for itr in mp:
            changes = max(changes, mp[itr])
        count += totalsize - changes
        left += 1
        right -= 1
    return count


if __name__ == '__main__':
    mat = [[1, 4, 1], [2, 5, 3], [1, 3, 1]]
    print(minchanges(mat))

# Expected output:
2
# count of longest possible subarrays with sum not divisible by k | function to find the count of longest subarrays with sum not divisible by k ; sum of all elements in an array ; if overall sum is not divisible then return 1 , as only one subarray of size n is possible ; index of the first number not divisible by k ; index of the last number not divisible by k ; subarray doesn 't exist ; sum of the window ; calculate the sum of rest of the windows of size len ; 
def CountLongestSubarrays(arr, n, k):
    s = 0
    for i in range(n):
        s += arr[i]
    if (s % k):
        return 1
    else:
        ini = 0
        while (ini < n and arr[ini] % k == 0):
            ini += 1
        final = n - 1
        while (final >= 0 and arr[final] % k == 0):
            final -= 1
        sum, count = 0, 0
        if (ini == n):
            return -1
        else:
            length = max(n - 1 - ini, final)
        for i in range(length):
            sum += arr[i]
        if (sum % k != 0):
            count += 1
        for i in range(length, n):
            sum = sum + arr[i]
            sum = sum + arr[i - length]
            if (sum % k != 0):
                count += 1
        return count


if __name__ == '__main__':
    arr = [3, 2, 2, 2, 3]
    n = len(arr)
    k = 3
    print(CountLongestSubarrays(arr, n, k))

# Expected output:
2
# check if a subsequence of length k with odd sum exists | function to check if any required subsequence exists or not ; store count of odd and even elements in the array ; calculate the count of odd and even elements ; if no odd element exists or no even element exists when k even ; subsequence is not possible ; otherwise possible ; 
def isSubseqPossible(arr, N, K):
    i = 0
    odd = 0
    even = 0
    for i in range(N):
        if (arr[i] % 2 == 1):
            odd += 1
        else:
            even += 1
    if (odd == 0 or (even == 0 and K % 2 == 0)):
        return False
    return True


if __name__ == '__main__':
    arr = [2, 3, 5, 7, 4]
    N = len(arr)
    K = 3
    print("Yes"if isSubseqPossible(arr, N, K)else "No")

# Expected output:
Yes
# path traversed using exactly m coins in k jumps | function that pr the path using exactly k jumps and m coins ; if no path exists ; it decides which box to be jump ; it decides whether to jump on left side or to jump on right side ; print the path ; 
def print_path(N, jump, coin):
    if (jump > coin or jump * (N - 1) < coin):
        print("-1")
    else:
        pos = 1
        while (jump > 0):
            tmp = min(N - 1, coin - (jump - 1))
            if (pos + tmp <= N):
                pos += tmp
            else:
                pos -= tmp
            print(pos, end=" ")
            coin -= tmp
            jump -= 1


N = 5
K = 4
M = 12
print_path(N, K, M)

# Expected output:
5 1 4 5
# minimum salary hike for each employee such that no employee feels unfair | python3 program for the above approach ; function that print minimum hike ; insert inf at begin and end of array ; to store hike of each employee ; for type 1 employee ; for type 2 employee ; for type 3 employee ; for type 4 employee ; print the min hike for each employee ; 

INF = 1e9


def findMinHike(arr, n):
    arr .insert(0, INF)
    arr .append(INF)
    hike = [0] * (n + 2)
    for i in range(1, n + 1):
        if (arr[i - 1] >= arr[i] and arr[i] <= arr[i + 1]):
            hike[i] = 1
    for i in range(1, n + 1):
        if (arr[i - 1] < arr[i] and arr[i] <= arr[i + 1]):
            hike[i] = hike[i - 1] + 1
    for i in range(1, n + 1):
        if (arr[i - 1] >= arr[i] and arr[i] > arr[i + 1]):
            hike[i] = hike[i + 1] + 1
    for i in range(1, n + 1):
        if (arr[i - 1] < arr[i] and arr[i] > arr[i + 1]):
            hike[i] = max(hike[i - 1], hike[i + 1]) + 1
    for i in range(1, n + 1):
        print(hike[i], end=" ")


if __name__ == '__main__':
    arr = [5, 3, 4, 2, 1, 6]
    findMinHike(arr, len(arr))

# Expected output:
2 1 3 2 1 2
# minimize the cost to make all the adjacent elements distinct in an array | function that prints minimum cost required ; dp - table ; base case not increasing the first element ; increasing the first element by 1 ; increasing the first element by 2 ; condition if current element is not equal to previous non - increased element ; condition if current element is not equal to previous element after being increased by 1 ; condition if current element is not equal to previous element after being increased by 2 ; take the minimum from all cases ; finding the minimum cost ; printing the minimum cost required to make all adjacent elements distinct ; 
def minimumCost(arr, cost, N):
    dp = [[0 for i in range(3)]for i in range(N)]
    dp[0][0] = 0
    dp[0][1] = cost[0]
    dp[0][2] = cost[0] * 2
    for i in range(1, N):
        for j in range(3):
            minimum = 1e6
            if (j + arr[i] != arr[i - 1]):
                minimum = min(minimum, dp[i - 1][0])
            if (j + arr[i] != arr[i - 1] + 1):
                minimum = min(minimum, dp[i - 1][1])
            if (j + arr[i] != arr[i - 1] + 2):
                minimum = min(minimum, dp[i - 1][2])
            dp[i][j] = j * cost[i] + minimum
    ans = 1e6
    for i in range(3):
        ans = min(ans, dp[N - 1][i])
    print(ans)


if __name__ == '__main__':
    arr = [1, 1, 2, 2, 3, 4]
    cost = [3, 2, 5, 4, 2, 1]
    N = len(arr)
    minimumCost(arr, cost, N)

# Expected output:
7
# subarray with largest sum after excluding its maximum element | function to find the maximum sum subarray by excluding the maximum element from the array ; loop to store all the positive elements in the map ; loop to iterating over the map and considering as the maximum element of the current including subarray ; make the current element maximum ; iterate through array and apply kadane 's algorithm ; condition if current element is greater than mx then make the element - infinity ; store the indices in some variable ; 
def maximumSumSubarray(arr, n):
    mp = {}
    for i in range(n):
        if (arr[i] >= 0 and arr[i]not in mp):
            mp[arr[i]] = 1
    first = 0
    last = 0
    ans = 0
    INF = 1e6
    for i in mp:
        mx = i
        curr = 0
        for j in range(n):
            if (curr == 0):
                curr_start = j
            if arr[j] > mx:
                val = -INF
            else:
                val = arr[j]
            curr += val
            if (curr < 0):
                curr = 0
            if (curr > ans):
                ans = curr
                first = curr_start
                last = j
    print(first + 1, last + 1)


if __name__ == "__main__":
    arr = [5, -2, 10, -1, 4]
    size = len(arr)
    maximumSumSubarray(arr, size)

# Expected output:
1 5