aboutsummaryrefslogtreecommitdiffstats
path: root/1339/main.go
blob: 8eed0772debfb4da921c7147038766c05e7eafc7 (plain) (blame)
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
package main

import (
	"fmt"
)

type TreeNode struct {
	Val   int
	Left  *TreeNode
	Right *TreeNode
}

func max(a, b int64) int64 {
	if a > b {
		return int64(a)
	} else {
		return int64(b)
	}
}

func maxProduct(root *TreeNode) int {
	var total int64
	var result int64

	var sumUnder func(*TreeNode) int64
	sumUnder = func(node *TreeNode) int64 {
		var sum int64
		if node == nil {
			return 0
		}

		sum = sumUnder(node.Left) + sumUnder(node.Right) + int64(node.Val)
		result = max(int64(result), sum*(total-sum))

		return sum
	}

	total = sumUnder(root)
	sumUnder(root)

	return int(result % (1_000_000_000 + 7))
}

func main() {
	fmt.Println("vim-go")
}