Guest User

Untitled

a guest
Nov 20th, 2018
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. // Given an array, you must increment any duplicate elements until all its elements are unique. In
  2. // addition, the sum of its elements must be the minimum possible within the rules. For example,
  3. // if arr = [3, 2, 1, 2, 7], then arrunique = [3, 2, 1, 4, 7] and its elements sum to a minimal
  4. // value of 3 + 2 + 1 + 4 + 7 = 17.
  5.  
  6.  
  7. // Function Description
  8.  
  9. // Complete the getMinimumUniqueSum function in the editor below to create an array of unique
  10. // elements with a minimal sum. Return the integer sum of the resulting array.
  11.  
  12. // getMinimumUniqueSum has the following parameter(s):
  13.  
  14. // arr: an array of integers to process
  15.  
  16. // Constraints
  17.  
  18. // 1 ≤ n ≤ 2000
  19. // 1 ≤ arr[i] ≤ 3000 where 0 ≤ i < n
  20. // Input Format For Custom Testing
  21.  
  22.  
  23. // Sample Case 0
  24.  
  25. // Sample Input 0
  26.  
  27. // 1
  28. // 2
  29. // 2
  30.  
  31. // Sample Output 0
  32.  
  33. // 6
  34.  
  35. // Explanation 0
  36.  
  37. // arr = [1, 2, 2]
  38.  
  39. // The duplicate array elements 2 must be addressed. The minimum unique array will be achieved by
  40. // incrementing one of the twos by 1, creating the array [1, 2, 3]. The sum of elements in the
  41. // new array is 1 + 2 + 3 = 6.
  42.  
  43. const assert = require('assert')
  44.  
  45. const arr = [3, 7, 7, 2, 1, 2, 7]
  46.  
  47. assert.strictEqual(getMinimumUniqueSum(arr), 32)
  48.  
  49. function getMinimumUniqueSum(numbers) {
  50. numbers.sort()
  51.  
  52. let ii = 0
  53. let length = numbers.length - 1
  54. for (let i = 0; i < length; i += 1) {
  55. let currentNumber = numbers[i]
  56. let nextNumber = numbers[i + 1]
  57.  
  58. if (currentNumber !== nextNumber) { continue }
  59.  
  60. numbers.splice(i, 1)
  61.  
  62. for (ii = Math.max(ii, i); ii < numbers.length; ii += 1) {
  63. const firstNumber = numbers[ii]
  64.  
  65. if (ii + 1 === numbers.length) {
  66. numbers.push(firstNumber + 1)
  67. length -= 1
  68. break;
  69. }
  70.  
  71. const secondNumber = numbers[ii + 1]
  72. if (firstNumber + 1 < secondNumber) {
  73. arr.splice(ii + 1, 0, firstNumber + 1)
  74. break
  75. }
  76. }
  77. }
  78.  
  79. return arr.reduce((sum, number) => sum + number, 0)
  80. }
Add Comment
Please, Sign In to add comment