Remove the element

You are given an integer array A of size N. You can perform an operation exactly N number of times. In the operation, you can remove one element from array A and the operation will cost 

Ai units if ith is removed from the array. The operation will take 1 second.

Elements of array A will keep on increasing every second until it is removed. Let ith element is Ai at jth second. Then the ith the element will increase by (j+1)Ai and the element will become Ai+(j+1)Ai at (j+1)th second.

Your task is to find the minimum cost to remove all the elements from array A. As the answer can be very large, print the answer module 109+7.

Example:

Input:  n = 2, arr = [3, 3]
Output: 9

Approach

C++

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

#define MOD 1000000007
long long dp[100001];
void fact(long long n)
{

    dp[1] = 1;
    for (long long i = 2i <= 100000i++)
        dp[i] = (i * dp[i - 1]) % MOD;
}

long long removeElement(long long nlong long arr[])
{
    sort(arrarr + n);
    long long ans = 0;
    long long j = 0;
    long long k = 1;
    for (long long i = n - 1i > 0i--)
    {
        ans = (ans + ((arr[i]) * dp[k]) % MOD) % MOD;
        k++;
    }
    ans = (ans + arr[0] * dp[n]) % MOD;
    return ans % MOD;
}
int main()
{

    fact(100000);

    long long n = 2;

    long long arr[n] = {33};

    cout << removeElement(narr<< "\n";

    return 0;
}


No comments:

Post a Comment