giulio98/xlcost-single-prompt huggingface dataset:
# find the maximum possible sum for the given conditions | function to find the maximum possible sum for the given conditions ; sorting the array ; variable to store the answer ; iterating through the array ; if the value is greater than 0 ; if the value becomes 0 then break the loop because all the weights after this index will be 0 ; print profit ; 
def maxProfit(arr):
    arr .sort(reverse=True)
    ans = 0
    for i in range(len(arr)):
        if (arr[i] - (1 * i)) > 0:
            ans += (arr[i] - (1 * i))
        if (arr[i] - (1 * i)) == 0:
            break
    return ans


if __name__ == "__main__":
    arr = [6, 6, 6]
    print(maxProfit(arr))

# Expected output:
15
# check if the array can be sorted only if the elements on given positions can be swapped | function to check if the array can be sorted only if the elements on the given positions can be swapped ; creating an array for marking the positions ; iterating through the array and mark the positions ; iterating through the given array ; if pos [ i ] is 1 , then incrementing till 1 is continuously present in pos ; sorting the required segment ; checking if the vector is sorted or not ; print yes if it is sorted ; 
def check_vector(A, n, p):
    pos = [0 for i in range(len(A))]
    for i in range(len(p)):
        pos[p[i] - 1] = 1
    flag = 1
    for i in range(n):
        if (pos[i] == 0):
            continue
        j = i
        while (j < n and pos[j]):
            j += 1
        p = A[:i]
        q = A[i:i + j + 1]
        r = A[i + j + 1:len(A)]
        q .sort(reverse=False)
        A = p + q + r
        i = j
    for i in range(n - 1):
        if (A[i] > A[i + 1]):
            flag = 0
            break
    if (flag == 1):
        print("Yes")
    else:
        print("No")


if __name__ == '__main__':
    A = [3, 2, 1]
    p = [1, 2]
    check_vector(A, len(A), p)

# Expected output:
Yes
# sort an array of strings based on the given order | python3 program to sort an array of strings based on the given order ; for storing priority of each character ; custom comparator function for sort ; loop through the minimum size between two words ; check if the characters at position i are different , then the word containing lower valued character is smaller ; when loop breaks without returning , it means the prefix of both words were same till the execution of the loop . now , the word with the smaller size will occur before in sorted order ; function to print the new sorted array of strings ; mapping each character to its occurrence position ; sorting with custom sort function ; printing the sorted order of words ; 

from functools import cmp_to_key
mp = {}


def comp(a, b):
    for i in range(min(len(a), len(b))):
        if (mp[a[i]] != mp[b[i]]):
            if mp[a[i]] < mp[b[i]]:
                return -1
            else:
                return 1
    if (len(a) < len(b)):
        return -1
    else:
        return 1


def printSorted(words, order):
    for i in range(len(order)):
        mp[order[i]] = i
    words = sorted(words, key=cmp_to_key(comp))
    for x in words:
        print(x, end=" ")


words = ["word", "world", "row"]
order = "worldabcefghijkmnpqstuvxyz"
printSorted(words, order)

# Expected output:
world word row
# sort elements of an array in increasing order of absolute difference of adjacent elements | function to sort the elements of the array by difference ; sorting the array ; array to store the elements of the array ; iterating over the length of the array to include each middle element of array ; appending the middle element of the array ; 
def sortDiff(arr, n):
    arr .sort()
    out = []
    while n:
        out .append(arr .pop(n // 2))
        n = n - 1
    print(*out)
    return out


if __name__ == "__main__":
    arr = [8, 1, 2, 3, 0]
    n = 5
    sortDiff(arr, n)

# Expected output:
2 3 1 8 0
# minimum cost of choosing the array element | function that find the minimum cost of selecting array element ; sorting the given array in increasing order ; to store the prefix sum of arr [ ] ; update the pref [ ] to find the cost selecting array element by selecting at most m element ; print the pref [ ] for the result ; 
def minimumCost(arr, N, M):
    arr .sort()
    pref = []
    pref .append(arr[0])
    for i in range(1, N):
        pref .append(arr[i] + pref[i - 1])
    for i in range(M, N):
        pref[i] += pref[i - M]
    for i in range(N):
        print(pref[i], end=' ')


arr = [6, 19, 3, 4, 4, 2, 6, 7, 8]
M = 2
N = len(arr)
minimumCost(arr, N, M)

# Expected output:
2 5 11 18 30 43 62 83 121
# sort an array alphabetically when each number is converted into words | variable to store the word form of units digit and up to twenty ; variable to store the word form of tens digit ; function to convert a two digit number to the word by using the above defined arrays ; if n is more than 19 , divide it ; if n is non - zero ; function to print a given number in words ; stores the word representation of the given number n ; handles digits at ten millions and hundred millions places ; handles digits at hundred thousands and one millions places ; handles digits at thousands and tens thousands places ; handles digit at hundreds places ; call the above function to convert the number into words ; function to sort the array according to the albhabetical order ; vector to store the number in words with respective elements ; inserting number in words with respective elements in vector pair ; sort the vector , this will sort the pair according to the alphabetical order . ; print the sorted vector content ; 

one = [
    "",
    "one ",
    "two ",
    "three ",
    "four ",
    "five ",
    "six ",
    "seven ",
    "eight ",
    "nine ",
    "ten ",
    "eleven ",
    "twelve ",
    "thirteen ",
    "fourteen ",
    "fifteen ",
    "sixteen ",
    "seventeen ",
    "eighteen ",
    "nineteen "]
ten = [
    "",
    "",
    "twenty ",
    "thirty ",
    "forty ",
    "fifty ",
    "sixty ",
    "seventy ",
    "eighty ",
    "ninety "]


def numToWords(n, s):
    st = ""
    if (n > 19):
        st += ten[n // 10] + one[n % 10]
    else:
        st += one[n]
    if (n):
        st += s
    return st


def convertToWords(n):
    out = ""
    out += numToWords((n // 10000000), "crore ")
    out += numToWords(((n // 100000) % 100), "lakh ")
    out += numToWords(((n // 1000) % 100), "thousand ")
    out += numToWords(((n // 100) % 10), "hundred ")
    if (n > 100 and n % 100):
        out += "and "
    out += numToWords((n % 100), "")
    return out


def sortArr(arr, n):
    vp = []
    for i in range(n):
        vp .append((convertToWords(arr[i]), arr[i]))
    vp .sort()
    for i in range(len(vp)):
        print(vp[i][1], end=" ")


if __name__ == "__main__":
    arr = [12, 10, 102, 31, 15]
    n = len(arr)
    sortArr(arr, n)

# Expected output:
15 102 10 31 12
# maximum possible rating of a coding contest | python3 program to find the maximum possible rating of a coding contest ; function to sort all problems descending to upvotes ; function to return maximum rating ; declaring vector of pairs ; each pair represents a problem with its points and upvotes ; step ( 1 ) - sort problems by their upvotes value in decreasing order ; declaring min_heap or priority queue to track of the problem with minimum points . ; step ( 2 ) - loop for i = 0 to k - 1 and do accordingly ; step ( 3 ) - loop for i = k to n - 1 and do accordingly ; 

import heapq


def Comparator(p1):
    return p1[1]


def FindMaxRating(N, Point, Upvote, K):
    vec = []
    for i in range(N):
        vec .append([Point[i], Upvote[i]])
    vec .sort(reverse=True, key=Comparator)
    pq = []
    heapq .heapify(pq)
    total_points, max_rating = 0, 0
    for i in range(K):
        total_points = (total_points + vec[i][0])
        max_rating = max(max_rating, total_points * vec[i][1])
        heapq .heappush(pq, vec[i][0])
    for i in range(K, N):
        if pq[0] < vec[i][0]:
            total_points = (total_points - pq[0] + vec[i][0])
            max_rating = max(max_rating, total_points * vec[i][1])
            heapq .heappop(pq)
            heapq .heappush(pq, vec[i][0])
    return max_rating


Point = [2, 10, 3, 1, 5, 8]
Upvote = [5, 4, 3, 9, 7, 2]
N = len(Point)
K = 2
print("Maximum Rating of Coding Contest is:",
      FindMaxRating(N, Point, Upvote, K))

# Expected output:
Maximum Rating of Coding Contest is: 60
# find sum of all unique elements in the array for k queries | function to find the sum of unique elements after q query ; updating the array after processing each query ; making it to 0 - indexing ; iterating over the array to get the final array ; variable to store the sum ; hash to maintain perviously occured elements ; loop to find the maximum sum ; 
def uniqueSum(A, R, N, M):
    for i in range(0, M):
        l = R[i][0]
        r = R[i][1] + 1
        l -= 1
        r -= 1
        A[l] += 1
        if (r < N):
            A[r] -= 1
    for i in range(1, N):
        A[i] += A[i - 1]
    ans = 0
    s = {chr}
    for i in range(0, N):
        if (A[i]not in s):
            ans += A[i]
        s .add(A[i])
    return ans


A = [0, 0, 0, 0, 0, 0]
R = [[1, 3], [4, 6], [3, 4], [3, 3]]
N = len(A)
M = len(R)
print(uniqueSum(A, R, N, M))

# Expected output:
6
# find the kth pair in ordered list of all possible sorted pairs of the array | function to find the k - th pair ; sorting the array ; iterating through the array ; finding the number of same elements ; checking if n * t is less than the remaining k . if it is , then arr [ i ] is the first element in the required pair ; printing the k - th pair ; 
def kthpair(n, k, arr):
    arr .sort()
    k -= 1
    i = 0
    while (i < n):
        t = 1
        while (arr[i] == arr[i + t]):
            t += 1
        if (t * n > k):
            break
        k = k - t * n
        i += t
    print(arr[i], " ", arr[k // t])


if __name__ == "__main__":
    n, k = 3, 2
    arr = [3, 1, 5]
    kthpair(n, k, arr)

# Expected output:
1   3
# minimum characters to be replaced to make frequency of all characters same | function to find the minimum operations to convert given string to another with equal frequencies of characters ; frequency of characters ; loop to find the frequency of each character ; sort in decreasing order based on frequency ; maximum possible answer ; loop to find the minimum operations required such that frequency of every character is equal ; 
def minOperations(s):
    freq = [0] * 26
    n = len(s)
    for i in range(n):
        freq[ord(s[i]) - ord('A')] += 1
    freq .sort(reverse=True)
    answer = n
    for i in range(1, 27):
        if (n % i == 0):
            x = n // i
            y = 0
            for j in range(i):
                y += min(freq[j], x)
            answer = min(answer, n - y)
    return answer


if __name__ == "__main__":
    s = "BBC"
    print(minOperations(s))

# Expected output:
1
# check if it is possible to sort an array with conditional swapping of elements at distance k | function for finding if it possible to obtain sorted array or not ; iterate over all elements until k ; store elements as multiples of k ; sort the elements ; put elements in their required position ; check if the array becomes sorted or not ; 
def fun(arr, n, k):
    v = []
    for i in range(k):
        for j in range(i, n, k):
            v .append(arr[j])
        v .sort()
        x = 0
        for j in range(i, n, k):
            arr[j] = v[x]
            x += 1
        v = []
    for i in range(n - 1):
        if (arr[i] > arr[i + 1]):
            return False
    return True


arr = [4, 2, 3, 7, 6]
K = 2
n = len(arr)
if (fun(arr, n, K)):
    print("yes")
else:
    print("no")

# Expected output:
no
# sort an array based on the absolute difference of adjacent elements | function that arrange the array such that all absolute difference between adjacent element are sorted ; to store the resultant array ; sorting the given array in ascending order ; variable to represent left and right ends of the given array ; traversing the answer array in reverse order and arrange the array elements from arr [ ] in reverse order ; inserting elements in zig - zag manner ; displaying the resultant array ; 
def sortedAdjacentDifferences(arr, n):
    ans = [0] * n
    arr = sorted(arr)
    l = 0
    r = n - 1
    for i in range(n - 1, -1, -1):
        if (i % 2):
            ans[i] = arr[l]
            l += 1
        else:
            ans[i] = arr[r]
            r -= 1
    for i in range(n):
        print(ans[i], end=" ")


if __name__ == '__main__':
    arr = [5, -2, 4, 8, 6, 4, 5]
    n = len(arr)
    sortedAdjacentDifferences(arr, n)

# Expected output:
5 4 5 4 6 -2 8
# minimum steps to convert an array into permutation of numbers from 1 to n | function to find minimum number of steps to convert a given sequence into a permutation ; sort the given array ; to store the required minimum number of operations ; find the operations on each step ; return the answer ; 
def get_permutation(arr, n):
    arr = sorted(arr)
    result = 0
    for i in range(n):
        result += abs(arr[i] - (i + 1))
    return result


if __name__ == '__main__':
    arr = [0, 2, 3, 4, 1, 6, 8, 9]
    n = len(arr)
    print(get_permutation(arr, n))

# Expected output:
7
# sort the major diagonal of the matrix | function to sort the major diagonal of the matrix ; loop to find the ith minimum element from the major diagonal ; loop to find the minimum element from the unsorted matrix ; swap to put the minimum element at the beginning of the major diagonal of matrix ; loop to print the matrix ; 
def sortDiagonal(a, M, N):
    for i in range(M):
        sm = a[i][i]
        pos = i
        for j in range(i + 1, N):
            if (sm > a[j][j]):
                sm = a[j][j]
                pos = j
        a[i][i], a[pos][pos] = a[pos][pos], a[i][i]
    for i in range(M):
        for j in range(N):
            print(a[i][j], end=" ")
        print()


a = [[4, 2], [3, 1]]
sortDiagonal(a, 2, 2)

# Expected output:
1 2 
3 4
# minimum cost to make an array a permutation of first n natural numbers | function to calculate minimum cost for making permutation of size n ; sorting the array in ascending order ; to store the required answer ; traverse the whole array ; return the required answer ; 
def make_permutation(arr, n):
    arr .sort()
    ans = 0
    for i in range(n):
        ans += abs(i + 1 - arr[i])
    return ans


if __name__ == "__main__":
    arr = [5, 3, 8, 1, 1]
    n = len(arr)
    print(make_permutation(arr, n))

# Expected output:
5
# find maximum sum from top to bottom row with no adjacent diagonal elements | function to find the maximum path sum from top to bottom row ; create an auxiliary array of next row with the element and it 's position ; sort the auxiliary array ; find maximum from row above to be added to the current element ; find the maximum element from the next row that can be added to current row element ; find the maximum sum ; 
def maxSum(V, n, m):
    ans = 0
    for i in range(n - 2, -1, -1):
        aux = []
        for j in range(m):
            aux .append([V[i + 1][j], j])
        aux = sorted(aux)
        aux = aux[::-1]
        for j in range(m):
            for k in range(m):
                if (aux[k][1] - j == 0 or abs(aux[k][1] - j) > 1):
                    V[i][j] += aux[k][0]
                    break
    for i in range(m):
        ans = max(ans, V[0][i])
    return ans


if __name__ == '__main__':
    V = [[1, 2, 3, 4], [8, 7, 6, 5], [10, 11, 12, 13]]
    n = len(V)
    m = len(V[0])
    print(maxSum(V, n, m))

# Expected output:
25
# count numbers whose maximum sum of distinct digit | function to find the digit - sum of a number ; loop to iterate the number digit - wise to find digit - sum ; variable to store last digit ; function to find the count of number ; vector to store the sum of digits ; sum of digits for each element in vector ; sorting the digitsum vector ; removing the duplicate elements ; count variable to store the count ; finding the count of numbers ; 
def SumofDigits(digit):
    sum = 0
    while (digit != 0):
        rem = digit % 10
        sum += rem
        digit //= 10
    return sum


def findCountofNumbers(arr, n, M):
    SumDigits = []
    for i in range(n):
        s = SumofDigits(arr[i])
        SumDigits .append(s)
    SumDigits .sort()
    ip = list(set(SumDigits))
    count = 0
    sum = 0
    for i in range(len(SumDigits)):
        if (sum > M):
            break
        sum += SumDigits[i]
        if (sum <= M):
            count += 1
    return count


if __name__ == "__main__":
    arr = [1, 45, 16, 17, 219, 32, 22]
    M = 10
    n = len(arr)
    print(findCountofNumbers(arr, n, M))

# Expected output:
3
# minimum sum of product of elements of pairs of the given array | function to find the minimum product ; sort the array using stl sort ( ) function ; initialise product to 1 ; find product of sum of all pairs ; return the product ; 
def minimumProduct(arr, n):
    arr = sorted(arr)
    product = 1
    for i in range(0, n, 2):
        product *= (arr[i] + arr[i + 1])
    return product


arr = [1, 6, 3, 1, 7, 8]
n = len(arr)
print(minimumProduct(arr, n))

# Expected output:
270
# minimum removals required to make ranges non |  ; sort by minimum starting point ; if the current starting point is less than the previous interval 's ending  point (ie. there is an overlap) ; increase rem ; remove the interval with the higher ending point ; 
def minRemovels(ranges):
    size = len(ranges)
    rem = 0
    ranges .sort()
    end = ranges[0][1]
    for i in range(1, size):
        if (ranges[i][0] < end):
            rem += 1
            end = min(ranges[i][1], end)
        else:
            end = ranges[i][1]
    return rem


if __name__ == '__main__':
    Input = [[19, 25], [10, 20], [16, 20]]
    print(minRemovels(Input))

# Expected output:
2
# sort the array by reversing the numbers in it | function to return the reverse of n ; function to sort the array according to the reverse of elements ; vector to store the reverse with respective elements ; inserting reverse with elements in the vector pair ; sort the vector , this will sort the pair according to the reverse of elements ; print the sorted vector content ; 
def reversDigits(num):
    rev_num = 0
    while (num > 0):
        rev_num = rev_num * 10 + num % 10
        num = num // 10
    return rev_num


def sortArr(arr, n):
    vp = []
    for i in range(n):
        vp .append((reversDigits(arr[i]), arr[i]))
    vp .sort()
    for i in range(len(vp)):
        print(vp[i][1], end=" ")


if __name__ == "__main__":
    arr = [12, 10, 102, 31, 15]
    n = len(arr)
    sortArr(arr, n)

# Expected output:
10 31 12 15 102
# count number of pairs with positive sum in an array | returns number of pairs in arr [ 0. . n - 1 ] with positive sum ; sort the array in increasing order ; intialise result ; intialise first and second pointer ; till the pointers doesn 't converge   traverse array to   count the pairs  ; if sum of arr [ i ] && arr [ j ] > 0 , then the count of pairs with positive sum is the difference between the two pointers ; increase the count ; 
def CountPairs(arr, n):
    arr .sort()
    count = 0
    l = 0
    r = n - 1
    while (l < r):
        if (arr[l] + arr[r] > 0):
            count += (r - l)
            r -= 1
        else:
            l += 1
    return count


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

# Expected output:
3
# partition the array into two odd length groups with minimized absolute difference between their median | function to find minimise the median between partition array ; sort the given array arr [ ] ; return the difference of two middle element of the arr [ ] ; 
def minimiseMedian(arr, n):
    arr .sort()
    ans = abs(arr[n // 2] - arr[(n // 2) - 1])
    return ans


if __name__ == "__main__":
    arr = [15, 25, 35, 50]
    n = len(arr)
    print(minimiseMedian(arr, n))

# Expected output:
10
# maximum number of overlapping intervals | function that prmaximum overlap among ranges ; variable to store the maximum count ; storing the x and y coordinates in data vector ; pushing the x coordinate ; pushing the y coordinate ; sorting of ranges ; traverse the data vector to count number of overlaps ; if x occur it means a new range is added so we increase count ; if y occur it means a range is ended so we decrease count ; updating the value of ans after every traversal ; printing the maximum value ; 
def overlap(v):
    ans = 0
    count = 0
    data = []
    for i in range(len(v)):
        data .append([v[i][0], 'x'])
        data .append([v[i][1], 'y'])
    data = sorted(data)
    for i in range(len(data)):
        if (data[i][1] == 'x'):
            count += 1
        if (data[i][1] == 'y'):
            count -= 1
        ans = max(ans, count)
    print(ans)


v = [[1, 2], [2, 4], [3, 6]]
overlap(v)

# Expected output:
2
# making three numbers equal with the given operations | function that returns true if a , b and c can be made equal with the given operations ; sort the three numbers ; find the sum of difference of the 3 rd and 2 nd element and the 3 rd and 1 st element ; subtract the difference from k ; check the required condition ; 
def canBeEqual(a, b, c, k):
    arr = [0] * 3
    arr[0] = a
    arr[1] = b
    arr[2] = c
    arr .sort()
    diff = 2 * arr[2] - arr[1] - arr[0]
    k = k - diff
    if (k < 0 or k % 3 != 0):
        return False
    return True


if __name__ == "__main__":
    a1 = 6
    b1 = 3
    c1 = 2
    k1 = 7
    if (canBeEqual(a1, b1, c1, k1)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# arrange numbers to form a valid sequence | function to organize the given numbers to form a valid sequence . ; sorting the array ; two pointer technique to organize the numbers ; 
def orgazineInOrder(vec, op, n):
    result = [0] * n
    vec .sort()
    i = 0
    j = n - 1
    k = 0
    while (i <= j and k <= n - 2):
        if (op[k] == '<'):
            result[k] = vec[i]
            i += 1
        else:
            result[k] = vec[j]
            j -= 1
        k += 1
    result[n - 1] = vec[i]
    return result


if __name__ == "__main__":
    vec = [8, 2, 7, 1, 5, 9]
    op = ['>', '>', '<', '>', '<']
    result = orgazineInOrder(vec, op, len(vec))
    for i in range(len(result)):
        print(result[i], end=" ")

# Expected output:
9 8 1 7 2 5
# find the distance between two person after reconstruction of queue | function to find the correct order and then return the distance between the two persons ; make pair of both height & infront and insert to vector ; sort the vector in ascending order ; find the correct place for every person ; insert into position vector according to infront value ; 
def getDistance(arr, n, a, b):
    vp = []
    for i in range(n):
        vp .append([arr[i][0], arr[i][1]])
    vp = sorted(vp)
    pos = [0 for i in range(n)]
    for i in range(len(vp)):
        height = vp[i][0]
        k = vp[i][1]
        pos[k] = height
    first = -1
    second = -1
    for i in range(n):
        if (pos[i] == a):
            first = i
        if (pos[i] == b):
            second = i
    return abs(first - second)


arr = [[5, 0], [3, 0], [2, 0], [6, 4], [1, 0], [4, 3]]
n = len(arr)
a = 6
b = 5
print(getDistance(arr, n, a, b))

# Expected output:
4
# minimize the sum of differences of consecutive elements after removing exactly k elements | function to find minimum sum ; variable to store final answer and initialising it with the values when 0 elements is removed from the left and k from the right . ; loop to simulate removal of elements ; removing i elements from the left and and k - i elements from the right and updating the answer correspondingly ; returning final answer ; 
def findSum(arr, n, k):
    ans = arr[n - k - 1] - arr[0]
    for i in range(1, k + 1):
        ans = min(arr[n - 1 - (k - i)] - arr[i], ans)
    return ans


if __name__ == "__main__":
    arr = [1, 2, 100, 120, 140]
    k = 2
    n = len(arr)
    print(findSum(arr, n, k))

# Expected output:
40