Best Index

You are given an array A of N elements. Now you need to choose the best index of this array A. An index of the array is called best if the special sum of this index is maximum across the special sum of all the other indices.

To calculate the special sum for any index i , you pick the first element that is A[i] and add it to your sum. Now you pick the next two elements i.e. A[i+1] and A[i+2] and add both of them to your sum. Now you will pick the next 3 elements and this continues till the index for which it is possible to pick the elements. For example:

If our array contains 10 elements and you choose index to be 3 then your special sum is denoted by -
(A[3])+(A[4]+A[5])+(A[6]+A[7]+A[8]) , beyond this its not possible to add further elements as the index value will cross the value 10.

Find the best index and in the output print its corresponding special sum. Note that there may be more than one best indices but you need to only print the maximum special sum.

Example:

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

Approach

C++

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

long long p[100001];

long long bestIndex(long long nvector<long long&arr)
{

    for (long long i = 1i <= ni++)
    {
        p[i] = p[i - 1] + arr[i - 1];
    }
    long long ans = -1000000000;
    for (int i = 1i <= ni++)
    {
        long long l = 1r = n;
        long long temp = 0;
        while (l <= r)
        {
            long long mid = (l + r) / 2;
            if (((mid * (mid + 1)) / 2) + i - 1 <= n)
            {
                temp = max(tempmid);
                l = mid + 1;
            }
            else
                r = mid - 1;
        }
        long long cnt = (temp * (temp + 1)) / 2;
        ans = max(ansp[i + cnt - 1] - p[i - 1]);
    }
    return ans;
}
int main()
{

    long long n = 5;
    vector<long longarr = {13125};

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

    return 0;
}


No comments:

Post a Comment