Best Index

PHOTO EMBED

Sun May 01 2022 00:59:05 GMT+0000 (Coordinated Universal Time)

Saved by @GreenMark #javascript

// Best Index
// Sample code to perform I/O:

process.stdin.resume();
process.stdin.setEncoding("utf-8");
var stdin_input = "";

process.stdin.on("data", function (input) {
    stdin_input += input;                               // Reading input from STDIN
});

process.stdin.on("end", function () {
   main(stdin_input);
});

function main(input) {
    var data= input.toString().split("\n");

    //process.stdout.write(bestIndex(data[1], parseInt(data[0])));
    console.log(bestIndex(data[1], parseInt(data[0])));
           // Writing output to STDOUT
}

// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail



// Write your code here
// Sample code to perform I/O:
//Enter your code here
function bestIndex(input,n) {
   

    let arr = input.split(" ").map((item)=>Number(item));

    let max = -Infinity;

    for (let i = 0; i<n; i++) {
        if (i>0) arr[i] = arr[i]+arr[i-1];
    }    
        
    
    for (let j = 0; j<n; j++) {
        let left = n- j;

        let sum =0;
        let k =Math.trunc(((-1+Math.sqrt((8*left+1)))/2));

        sum=arr[Math.trunc((k*(k+1))/2+j-1)];

        if (j!=0) {sum-=arr[j-1];}
        if (max<sum) {max=sum;}
        


        
    }    

    
    return max.toString();

}
content_copyCOPY

Problem 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 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. Input First line contains an integer as input. Next line contains space separated integers denoting the elements of the array . Output In the output you have to print an integer that denotes the maximum special sum Constraints Sample Inputs Input Output 5 1 3 1 2 5 8 10 2 1 3 9 2 4 -10 -9 1 3 9 Sample Input 6 -3 2 3 -4 3 1 Sample Output 3

https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/best-index-1-45a2f8ff/