Hi,
I am teaching myself Go by doing simple programming challenges. One problem I have solved in Python is this one:
https://codeforces.com/contest/463/problem/B
My code in Python that passes all the tests is as follows:
import math
import os
file = os.sys.stdin
n = int(file.readline().split(' ')[0])
heights = file.readline().split(' ')
heights.insert(0, 0)
cost = 0
energy = 0
for i, _ in enumerate(heights):
if i == 0:
continue
gain = int(heights[i - 1]) - int(heights[i])
energy += gain
if energy < 0:
cost += -energy
energy = 0
print(cost)
However, when I translate this to Go, my solution fails. My solution in Go:
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
n, err := strconv.Atoi(scanner.Text())
check(err)
scanner.Scan()
heights := strings.Fields(scanner.Text())
heights = append([]string{"0"}, heights...)
cost := 0
energy := 0
for i := 1; i <= n; i ++ {
a, err := strconv.Atoi((heights[i - 1]))
check(err)
b, err := strconv.Atoi((heights[i]))
check(err)
gain := a - b
energy += gain
if energy < 0 {
cost += -energy
energy = 0
}
}
fmt.Println(cost)
}
func check(err error) {
if err != nil {
fmt.Println(err)
panic(err)
}
}
The reason is that it fails Test 9. Here is the error message:
Now it seems something is going wrong with the string conversion. I have read the documents but cannot figure out what is going on. Could someone please guide me through what this could be?
Instead of strings.Split() I also used the strings.Fields() function, but that also failed.
Thank you!