-
-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathtask.go
69 lines (60 loc) · 1.12 KB
/
task.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package main
import (
"bufio"
"fmt"
"io"
"log"
"os"
"strconv"
"strings"
)
type Price struct {
day int
price int
currentPick bool
}
func main() {
s := strings.Builder{}
Solution(os.Stdin, &s)
fmt.Println(s.String())
}
func Solution(r io.Reader, s *strings.Builder) {
scanner := bufio.NewScanner(r)
scanner.Scan()
n, err := strconv.Atoi(scanner.Text())
if err != nil {
log.Fatal(err)
}
scanner.Scan()
priceArr := strings.Fields(scanner.Text())
priceData := make([]Price, 0, n)
for i, priceStr := range priceArr {
price, err := strconv.Atoi(priceStr)
if err != nil {
log.Fatal(err)
}
priceData = append(priceData, Price{
day: i,
price: price,
})
}
var lowPick Price
value := 0
for i := 0; i < n; i++ {
if !lowPick.currentPick {
if i+1 < n &&
priceData[i+1].price < priceData[i].price {
continue
}
lowPick = priceData[i]
lowPick.currentPick = true
continue
}
if i+1 < n && priceData[i].price < priceData[i+1].price {
continue
}
value += priceData[i].price - lowPick.price
lowPick.currentPick = false
}
s.WriteString(fmt.Sprint(value))
}