Created
March 26, 2016 02:39
-
-
Save vicneanschi/935ae04eea05d253008e to your computer and use it in GitHub Desktop.
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
| // https://www.hackerrank.com/challenges/maximise-sum | |
| function processData(input) { | |
| var lines = input.split('\n') | |
| var line = 0; | |
| var t = parseInt(lines[line++]); | |
| for (var i = 0; i < t; i++){ | |
| var tmp = lines[line++].split(' ').map(x => parseInt(x)); | |
| var n = tmp[0], m = tmp[1]; | |
| var arr = lines[line++].split(' ').map(x => parseInt(x)).slice(0, n); | |
| console.log(solution(arr, m)); | |
| } | |
| } | |
| function solution(arr, m){ | |
| var prefix = []; | |
| var sum = 0; | |
| var n = arr.length; | |
| var i, j; | |
| for (i = 0; i < n; i++){ | |
| sum += arr[i]; | |
| prefix[i] = {value: sum % m, index: i}; | |
| // optimization: m-1 is the maximum we can get | |
| if (prefix[i].value === m-1) return m-1; | |
| } | |
| prefix.sort((a, b) => a.value - b.value); | |
| //console.log(prefix); | |
| var minDiff = m - prefix[n-1].value; | |
| //console.log(minDiff); | |
| for (i = 1; i < n; i++){ | |
| if (prefix[i-1].index > prefix[i].index && prefix[i].value - prefix[i-1].value > 0) { | |
| minDiff = Math.min(minDiff, (prefix[i].value - prefix[i-1].value)); | |
| } | |
| } | |
| return m - minDiff; | |
| } | |
| process.stdin.resume(); | |
| process.stdin.setEncoding("ascii"); | |
| _input = ""; | |
| process.stdin.on("data", function (input) { | |
| _input += input; | |
| }); | |
| process.stdin.on("end", function () { | |
| processData(_input); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment