Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 3c36de4

Browse files
author
Sandy
authored
Merge pull request #217 from openset/develop
Add: Maximum Product of Three Numbers
2 parents 94d167e + 6366e9f commit 3c36de4

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-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: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,35 @@
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+
input: []int{-1, -2, -3, 5, 4, 3, 2, 1},
26+
expected: 60,
27+
},
28+
}
29+
for _, tc := range tests {
30+
output := maximumProduct(tc.input)
31+
if output != tc.expected {
32+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
33+
}
34+
}
35+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /