Skip to content

Instantly share code, notes, and snippets.

@PantherHawk
Created December 14, 2017 17:14
Show Gist options
  • Save PantherHawk/1276ef8e29093b1fa7f30b0241b1fcfb to your computer and use it in GitHub Desktop.
Save PantherHawk/1276ef8e29093b1fa7f30b0241b1fcfb to your computer and use it in GitHub Desktop.

Requirements

Given a list of integers, return the number of times it takes produce a list of equal integers by incrementing n - 1 elements by one.

Strategy

Maths!

Justification of strategy

The largest number in the list, x, is greater than or equal to the product of s, the smallest number, 1, the number we increment the smallest number by, and m, the number of times we increment, and the value we're after. ![equation](x <= 1 * m) Refactoring, we find that the product of m and the number of elements we increment equals the difference between the sum of all elements and the product of the largest element and the number of elements. ![equation](m*(n-1) = sum-x*n >= sum-(minNum+m)n) Refactoring again, we get ![equation](m <= sum-(minNum)*n) Just solve for equation

Define test cases

  • minToEqual([1, 2, 3]) should return 3
  • minToEqual([1, 50000]) should return 49999

Implementation skeleton

  • a: solve for sum of elements
  • b: solve for minimum value
  • c: solve for length of list
  • return a - (b * c)

Actual implementation

function minMoves(list) {
  var sum = list.reduce((a, b) => a + b)
  var minNum = Math.min(...list)
  var n = list.length;
  return sum-(minNum)*n
}

Execute test cases

Big-O Analysis

O(n), Linear because of reduce method.

Optimization (if applicable)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment