Created
May 20, 2020 00:11
-
-
Save rakibulalam/6526295a62dc4f22bd7cada5c80cde12 to your computer and use it in GitHub Desktop.
Hourglass Sum Hacker Rank
This file contains 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 hourglassSum function below. | |
function hourglassSum(arr) { | |
const n = arr.length; | |
let max = 0; | |
for (let i = 0; i < n - 2; i++) { | |
const sn = arr[i].length; | |
for (let j = 0; j < sn - 2; j++) { | |
if (i + 2 < n && j + 2 < sn) { | |
const sum = arr[i][j] + arr[i][j + 1] + arr[i][j + 2] + arr[i + 1][j + 1] + arr[i + 2][j] + arr[i + 2][j + 1] + arr[i + 2][j + 2]; | |
max = max <= sum || (max === 0 && i === 0) ? sum : max; | |
} | |
} | |
} | |
return max; | |
} | |
function main() { | |
const ws = fs.createWriteStream(process.env.OUTPUT_PATH); | |
let arr = Array(6); | |
for (let i = 0; i < 6; i++) { | |
arr[i] = readLine().split(' ').map(arrTemp => parseInt(arrTemp, 10)); | |
} | |
let result = hourglassSum(arr); | |
ws.write(result + "\n"); | |
ws.end(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment