Skip to content

Commit 3ecd2bc

Browse files
committed
Add: Maximum Product of Three Numbers
1 parent 189a59c commit 3ecd2bc

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,27 @@
11
package maximum_product_of_three_numbers
2+
3+
import "math"
4+
5+
func maximumProduct(nums []int) int {
6+
min1, min2 := math.MaxInt32, math.MaxInt32
7+
max1, max2, max3 := math.MinInt32, math.MinInt32, math.MinInt32
8+
for _, n := range nums {
9+
if n < min1 {
10+
min1, min2 = n, min1
11+
} else if n < min2 {
12+
min2 = n
13+
}
14+
if n > max3 {
15+
max1, max2, max3 = max2, max3, n
16+
} else if n > max2 {
17+
max1, max2 = max2, n
18+
} else if n > max1 {
19+
max1 = n
20+
}
21+
}
22+
ans1, ans2 := min1*min2*max3, max1*max2*max3
23+
if ans1 > ans2 {
24+
return ans1
25+
}
26+
return ans2
27+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,31 @@
11
package maximum_product_of_three_numbers
2+
3+
import "testing"
4+
5+
type caseType struct {
6+
input []int
7+
expected int
8+
}
9+
10+
func TestMaximumProduct(t *testing.T) {
11+
tests := [...]caseType{
12+
{
13+
input: []int{1, 2, 3},
14+
expected: 6,
15+
},
16+
{
17+
input: []int{1, 2, 3, 4},
18+
expected: 24,
19+
},
20+
{
21+
input: []int{-2, -1, 0, 2, 3},
22+
expected: 6,
23+
},
24+
}
25+
for _, tc := range tests {
26+
output := maximumProduct(tc.input)
27+
if output != tc.expected {
28+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
29+
}
30+
}
31+
}

0 commit comments

Comments
 (0)