Minimum additions

You are given an array A of N positive integers. Your task is to add a minimum number of non-negative integers to the array such that the floor of an average array A becomes less than or equal to K.

The floor of an average array A containing N integers are equal to ⌊∑i=1NAiN⌋. Here ⌊.⌋ is the floor function. 

Example:

Input:  n = 2, k = 1, arr = {3, 1}
Output: 1

Approach

Java

public class MinimumAdditions {
    public static void main(String[] args) {

        long n = 2, k = 1;

        long arr[] = { 3, 1 };

        System.out.println(minimumAdditions(n, k, arr));

    }

    static long minimumAdditions(long n, long k, long arr[]) {
        long sum = 0;
        for (int i = 0; i < n; i++) {
            sum += arr[i];
        }
        long floor;
        floor = sum / n;
        if (floor <= k)
            return 0;
        else {
            long R = (long) 1e18, extra = 0, L = n, mid;
            while (L <= R) {
                mid = (L + R) / 2;
                floor = sum / mid;
                if (floor <= k) {
                    extra = mid;
                    R = mid - 1;
                } else {
                    L = mid + 1;
                }
            }
            return extra - n;
        }
    }

}

C++

#include <bits/stdc++.h>
using namespace std;

long long minimumAdditions(long long n, long long k,
                           vector<long long> arr)
{
    long long sum = 0;
    for (long long i = 0; i < n; i++)
    {
        sum += arr[i];
    }
    long long floor;
    floor = sum / n;
    if (floor <= k)
        return 0;
    else
    {
        long long int R = 1e18, extra, L = n, mid;
        while (L <= R)
        {
            mid = (L + R) / 2;
            floor = sum / mid;
            if (floor <= k)
            {
                extra = mid;
                R = mid - 1;
            }
            else
            {
                L = mid + 1;
            }
        }
        return extra - n;
    }
}
int main()
{

    //for fast input output
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    long long n = 2, k = 1;

    vector<long long> arr = {3, 1};

    cout << minimumAdditions(n, k, arr) << "\n";

    return 0;
}


No comments:

Post a Comment