pythonlistreduction

Stuck in writing python list reduction program


I am stuck in writing the python code for below problem, can anyone help to find the issue with the code is much appreciated.

List Reduction:

You are given a list of integers L having size N and an integer K. You can perform the following operation on the list at most k times:

Note: that after such an operation, the list is changed and the changed list will be used in subsequent operations.

You need to minimize the sum of all elements present in the list after performing at most k such operations.

Input Format:

Output Format:

Print the minimum possible sum of all elements in the list at the end, after performing at most k operations.

Code:

def solve (X, arr):
    Sum = 0
    largestDivisible, minimum = -1, arr[0]
    for i in range(0,N):
        Sum += arr[i]
        if(arr[i]%X == 0 and largestDivisible < arr[i]):
            largestDivisible = arr[i]
        if arr[i] < minimum:
            minimum = arr[i]
    if largestDivisible == -1:
        return Sum

    sumAfterOperation = (Sum-minimum-largestDivisible+(X*minimum)+(largestDivisible//X))
    return min(Sum,sumAfterOperation)
    

N=5 
X =2
#map(int, input().split())
arr = [10, 7, 4, 2, 1]
#list(map(int, input().split()))

out_ = solve(X, arr)
print (out_)
output: 20

expected output: 19


Solution

  • Not optimal program.

    Idea: Multiplying the minimal element and dividing the maximal element gives sequence with minimal total sum. Do you want process negative numbers? Does K take negative values?

    K = int(input())
    arr = list(map(int, input().split()))
    
    for _ in range(K):
        arr.sort()
        arr[0] *= 2
        arr[-1] = arr[-1] // 2 + arr[-1] % 2
    
    print(sum(arr))
    

    More effective solution.

    K = int(input())
    arr = list(map(int, input().split()))
    
    for _ in range(K):
        mn, mx = min(arr), max(arr)
        mn_i = arr.index(mn)
        if mn != mx:
            mx_i = arr.index(mx)
        else:
            mx_i = arr.index(mx, mn_i+1)
        arr[mn_i] *= 2
        arr[mx_i] = arr[mx_i] // 2 + arr[mx_i] % 2
    print(sum(arr))
    

    And algorithmic solution.

    K = int(input())
    arr = list(map(int, input().split()))
    
    for _ in range(K):
        mn, mx = 0, 0
        for i, x in enumerate(arr):
            if x < arr[mn]:
                mn = i
            if x >= arr[mx]:
                mx = i
        arr[mn] *= 2
        arr[mx] = arr[mx] // 2 + arr[mx] % 2
    
    print(sum(arr))