In this Leetcode Best Index problem solution, 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 the 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 index but you need to only print the maximum special sum.

hackerEarth Best Index problem solution


HackerEarth Best Index problem solution.

#include<bits/stdc++.h>
#define LL long long int
#define M 1000000007
#define endl "\n"
#define eps 0.00000001
#define check(a , b , c) assert(a >= b && a <= c)
LL pow(LL a,LL b,LL m){LL x=1,y=a;while(b > 0){if(b%2 == 1){x=(x*y);if(x>m) x%=m;}y = (y*y);if(y>m) y%=m;b /= 2;}return x%m;}
LL gcd(LL a,LL b){if(b==0) return a; else return gcd(b,a%b);}
LL gen(LL start,LL end){LL diff = end-start;LL temp = rand()%start;return temp+diff;}
using namespace std;
LL p[100001];
int main()
    {
        ios_base::sync_with_stdio(0);
        int n;
        cin >> n;
        assert(n <= 100000);
        for(int i = 1; i <= n; i++)
            {
                LL val;
                cin >> val;
                assert(abs(val) <= 10000000);
                p[i] = p[i - 1] + val;
            }
        LL ans = -1000000000;
        for(int i = 1; i <= n; i++)
            {
                LL l = 1 , r = n;
                LL temp = 0;
                while(l <= r)
                    {   
                        LL mid = (l + r) / 2;
                        if(((mid * (mid + 1)) / 2) + i - 1 <= n)
                            {
                                temp = max(temp , mid);
                                l = mid + 1;
                            }
                        else
                                r = mid - 1;
                    }
                LL cnt = (temp * (temp + 1)) / 2;
                ans = max(ans , p[i + cnt - 1] - p[i - 1]);
            }
        cout << ans;
        
    }