Skip to content

Commit e27f07f

Browse files
authored
Add Maximum Array Rotation in Go (#4514)
1 parent 4620949 commit e27f07f

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"os"
6+
"unicode"
7+
)
8+
9+
func main() {
10+
if len(os.Args) != 2 {
11+
printError()
12+
} else {
13+
if len(createSlice()) == 0 {
14+
printError()
15+
} else {
16+
fmt.Println(getMaxWeightedSum(createSlice()))
17+
}
18+
}
19+
}
20+
21+
func createSlice() (slice []int) {
22+
stringSlice := os.Args[1]
23+
for _, char := range stringSlice {
24+
if unicode.IsDigit(char) {
25+
slice = append(slice, int(char)-'0')
26+
}
27+
}
28+
return
29+
}
30+
31+
func getWeightedSum(slice []int) (sum int) {
32+
for i, num := range slice {
33+
sum += i * num
34+
}
35+
return
36+
}
37+
38+
func getMaxWeightedSum(slice []int) (max int) {
39+
max = 0
40+
for i := 0; i < len(slice); i++ {
41+
if getWeightedSum(slice) > max {
42+
max = getWeightedSum(slice)
43+
}
44+
slice = rotateSlice(slice)
45+
}
46+
return
47+
}
48+
49+
func rotateSlice(slice []int) (rotatedSlice []int) {
50+
first := slice[0]
51+
slice = slice[1:]
52+
slice = append(slice, first)
53+
rotatedSlice = slice
54+
return
55+
}
56+
57+
func printError() {
58+
fmt.Println("Usage: please provide a list of integers (e.g. \"8, 3, 1, 2\")")
59+
}

0 commit comments

Comments
 (0)