You are given an array of elements. Now you need to choose the best index of this array . 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 , you pick the first element that is and add it to your sum. Now you pick the next two elements i.e. and and add both of them to your sum. Now you will pick the next elements and this continues till the index for which it is possible to pick the elements. For example:
If our array contains elements and you choose index to be then your special sum is denoted by -
, beyond this its not possible to add further elements as the index value will cross the value .
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 n, vector<long long> &arr){for (long long i = 1; i <= n; i++){p[i] = p[i - 1] + arr[i - 1];}long long ans = -1000000000;for (int i = 1; i <= n; i++){long long l = 1, r = n;long long temp = 0;while (l <= r){long long mid = (l + r) / 2;if (((mid * (mid + 1)) / 2) + i - 1 <= n){temp = max(temp, mid);l = mid + 1;}elser = mid - 1;}long long cnt = (temp * (temp + 1)) / 2;ans = max(ans, p[i + cnt - 1] - p[i - 1]);}return ans;}int main(){long long n = 5;vector<long long> arr = {1, 3, 1, 2, 5};cout << bestIndex(n, arr) << "\n";return 0;}
No comments:
Post a Comment