Skip to content

Instantly share code, notes, and snippets.

@mmirolim
Created May 8, 2018 15:32
Show Gist options
  • Save mmirolim/d4052a8183db84761b306f43da30c4f9 to your computer and use it in GitHub Desktop.
Save mmirolim/d4052a8183db84761b306f43da30c4f9 to your computer and use it in GitHub Desktop.
package maxproduct
import "fmt"
// find max product of 3 numbers
func maxProduct(ints []int) int {
// scan for 3 max values and 2 smallest numbers (possible negative)
max := 0
// 32 bit
minVal := 1<<31 - 1
maxVal := 1<<31 - 1
var max1, max2, max3 = -maxVal, -maxVal, -maxVal
var min1, min2 = minVal, minVal
for _, v := range ints {
if v >= max1 {
max1, max2, max3 = v, max1, max2
} else if v >= max2 {
max2, max3 = v, max2
} else if v >= max3 {
max3 = v
}
if v <= min1 {
min1, min2 = v, min1
} else if v <= min2 {
min2 = v
}
}
fmt.Printf("%d %d %d\n", max1, max2, max3) // output for debug
fmt.Printf("%d %d \n", min1, min2) // output for debug
if max1*max2*max3 > min1*min2*max1 {
max = max1 * max2 * max3
} else {
max = min1 * min2 * max1
}
return max
}
/*
package maxproduct
import (
"testing"
)
func TestMaxProduct(t *testing.T) {
cases := []struct {
in []int
want int
}{
{in: []int{-5, 3, 2, 10}, want: 60},
{in: []int{-5, -3, -4, 2, 2, 10}, want: 200},
}
for i, tc := range cases {
out := maxProduct(tc.in)
if tc.want != out {
t.Errorf("case %d, want %d, got %d", i, tc.want, out)
}
}
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment