Created
May 22, 2020 17:54
-
-
Save rakibulalam/d52b6dd555a96767569ff2675d624d50 to your computer and use it in GitHub Desktop.
Array Manipulation Hacker Rank
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const fs = require('fs'); | |
process.stdin.resume(); | |
process.stdin.setEncoding('utf-8'); | |
let inputString = ''; | |
let currentLine = 0; | |
process.stdin.on('data', inputStdin => { | |
inputString += inputStdin; | |
}); | |
process.stdin.on('end', _ => { | |
inputString = inputString.replace(/\s*$/, '') | |
.split('\n') | |
.map(str => str.replace(/\s*$/, '')); | |
main(); | |
}); | |
function readLine() { | |
return inputString[currentLine++]; | |
} | |
// Complete the arrayManipulation function below. | |
function arrayManipulation(n, queries) { | |
// problem is known as prefix sum algo. | |
const arr = new Array(n + 2).fill(0), qn = queries.length; | |
let sum = 0, maxValue = 0; | |
for (let i = 0; i < qn; i++) { | |
const [min, max, sum] = queries[i]; | |
arr[min] += sum; | |
maxValue = maxValue < sum ? sum : maxValue | |
if (max <= n) { | |
arr[max + 1] -= sum; | |
} | |
} | |
for (let k = 0; k < n; k++) { | |
sum += arr[k]; | |
if (maxValue < sum) { | |
maxValue = sum; | |
} | |
} | |
return maxValue; | |
} | |
function main() { | |
const ws = fs.createWriteStream(process.env.OUTPUT_PATH); | |
const nm = readLine().split(' '); | |
const n = parseInt(nm[0], 10); | |
const m = parseInt(nm[1], 10); | |
let queries = Array(m); | |
for (let i = 0; i < m; i++) { | |
queries[i] = readLine().split(' ').map(queriesTemp => parseInt(queriesTemp, 10)); | |
} | |
let result = arrayManipulation(n, queries); | |
ws.write(result + "\n"); | |
ws.end(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment