Skip to content

Instantly share code, notes, and snippets.

@zard1989
Created July 10, 2010 17:13
Show Gist options
  • Select an option

  • Save zard1989/470870 to your computer and use it in GitHub Desktop.

Select an option

Save zard1989/470870 to your computer and use it in GitHub Desktop.
sub dist_square_sum {
my @array = @_;
my ($sum, $sum_sq, $r);
$sum = $sum_sq = $r = 0;
for (@array) { # O(N)
$sum += $_; # O(1)
$sum_sq += $_**2; # O(1)
}
for (0..$#array-1) { # O(N)
$sum -= $array[$_]; # O(1)
$r += -2*$array[$_]*$sum; # O(1)
}
return (@array-1)*$sum_sq + $r; # O(1)
# total: O(N)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment