mercredi 15 décembre 2021

Please solve and explain BEST INDEX Question of HackerEarth Question and explain the code described below in C++ language

This is the following C++ Hackerearth Question, which I found a solution but couldn't understand it.

Here's the Question:

Problem img1

Problem img2

Problem img3

Problem img4

CODE:

#include <iostream>
#include <math.h>
using namespace std;

int main() {
    int n;
    cin >> n;
    long a[n];
    
    for(int i=0;i<n;i++) {
        cin>>a[i];
        a[i]+=a[i-1];
        }
    
    long max=a[n-1]-a[n-2];
    
    for(int i=1;i<n-1;i++) {

        int k;
    
        k = (-1+sqrt(1+8*(n-i)))/2;
    
        k = (k*(k+1))/2;
    
        if((a[k+i-1]-a[i-1])>max) {

            max=a[k+i-1]-a[i-1];
    
        }
    
    }
    cout<<max;
}

So in this Question can you please explain the logic behind this code? I'm a beginner in programming.

  1. k = (-1+sqrt(1+8*(n-i)))/2; k = (k*(k+1))/2; How did these 2 expressions come into picture? logic behind this.
  2. If loop explanation?

Aucun commentaire:

Enregistrer un commentaire