Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Given an array, you must increment any duplicate elements until all its elements are unique. In
- // addition, the sum of its elements must be the minimum possible within the rules. For example,
- // if arr = [3, 2, 1, 2, 7], then arrunique = [3, 2, 1, 4, 7] and its elements sum to a minimal
- // value of 3 + 2 + 1 + 4 + 7 = 17.
- // Function Description
- // Complete the getMinimumUniqueSum function in the editor below to create an array of unique
- // elements with a minimal sum. Return the integer sum of the resulting array.
- // getMinimumUniqueSum has the following parameter(s):
- // arr: an array of integers to process
- // Constraints
- // 1 ≤ n ≤ 2000
- // 1 ≤ arr[i] ≤ 3000 where 0 ≤ i < n
- // Input Format For Custom Testing
- // Sample Case 0
- // Sample Input 0
- // 1
- // 2
- // 2
- // Sample Output 0
- // 6
- // Explanation 0
- // arr = [1, 2, 2]
- // The duplicate array elements 2 must be addressed. The minimum unique array will be achieved by
- // incrementing one of the twos by 1, creating the array [1, 2, 3]. The sum of elements in the
- // new array is 1 + 2 + 3 = 6.
- const assert = require('assert')
- const arr = [3, 7, 7, 2, 1, 2, 7]
- assert.strictEqual(getMinimumUniqueSum(arr), 32)
- function getMinimumUniqueSum(numbers) {
- numbers.sort()
- let ii = 0
- let length = numbers.length - 1
- for (let i = 0; i < length; i += 1) {
- let currentNumber = numbers[i]
- let nextNumber = numbers[i + 1]
- if (currentNumber !== nextNumber) { continue }
- numbers.splice(i, 1)
- for (ii = Math.max(ii, i); ii < numbers.length; ii += 1) {
- const firstNumber = numbers[ii]
- if (ii + 1 === numbers.length) {
- numbers.push(firstNumber + 1)
- length -= 1
- break;
- }
- const secondNumber = numbers[ii + 1]
- if (firstNumber + 1 < secondNumber) {
- arr.splice(ii + 1, 0, firstNumber + 1)
- break
- }
- }
- }
- return arr.reduce((sum, number) => sum + number, 0)
- }
Add Comment
Please, Sign In to add comment