题解 | #最大乘积#
最大乘积
https://www.nowcoder.com/practice/5f29c72b1ae14d92b9c3fa03a037ac5f
package main import ( "fmt" ) //时间复杂度O(N*logN) //空间复杂度O(1) func main() { a := 0 _, _ = fmt.Scan(&a) //fmt.Println(a) nums := make([]int, a) for i:=0; i < a; i++ { b := 0 _, _ = fmt.Scan(&b) nums[i] = b } //fmt.Println(nums) quickSort(nums, 0, len(nums)-1) //fmt.Println(nums) //如果最大开始三个都是正数 //最大前一个是正数 后面开始是负的最小两个数值 //为0则跳过 a = 0 if len(nums) >= 3 && nums[0] > 0 && nums[1] > 0 && nums[2] > 0 { a = nums[0]*nums[1]*nums[2] } b := 0 if len(nums) >= 3 && nums[len(nums)-1] < 0 && nums[len(nums)-2] < 0 && nums[0] > 0 { b = nums[len(nums)-1] * nums[len(nums)-2] * nums[0] } if a > b { fmt.Println(a) }else { fmt.Println(b) } } func quickSort(nums []int, left ,right int) { if left >= right { return } p := getPartition(nums, left, right) quickSort(nums, left, p-1) quickSort(nums, p+1, right) } func getPartition(nums []int, left, right int) int { sentry := nums[right] i := left for j := left; j <= right; j++ { if nums[j] > sentry { nums[i], nums[j] = nums[j], nums[i] i++ } } nums[i], nums[right] = sentry, nums[i] return i }