import "sort"
func min(x,y int) int{
if x < y {
return x
}
return y
}
func arrayPairSum(nums []int) int {
answer := 0
sort.Slice(nums, func(i,j int) bool { return nums[i] < nums[j] })
//fmt.Printf("%v\n", nums)
for i := 0; i < len(nums); i+=2 {
answer += min(nums[i], nums[i+1])
}
return answer
}
Given an integer array nums of 2n integers, group these integers into n pairs (a1, b1), (a2, b2), ..., (an, bn) such that the sum of min(ai, bi) for all i is maximized. Return the maximized sum.
Example 1:
Input: nums = [1,4,3,2]
Output: 4
Explanation: All possible pairings (ignoring the ordering of elements) are:
1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3
2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3
3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4
So the maximum possible sum is 4.
Example 2:
Input: nums = [6,2,6,5,1,2]
Output: 9
Explanation: The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9.
Constraints:
func arrayPairSum(nums []int) int {
length := len(nums)
sum := 0
maxi := 0
counter := 0
for length > 0 {
max := math.MinInt
for i := 0; i < length; i++ {
if max <= nums[i] {
max = nums[i]
maxi = i
}
}
nums = append(nums[:maxi], nums[maxi+1:]...)
counter++
length--
if counter%2 == 0 {
sum += max
}
}
return sum
}
func arrayPairSum(nums []int) int {
sort.Ints(nums)
sum := 0
for i:=0; i<len(nums); i+=2 {
sum += nums[i]
}
return sum
}
func arrayPairSum(nums []int) int {
arr := make([]int, 20001)
for _, v := range nums {
arr[v+10000]++
}
var sum int
flag := true
for i := 0; i < len(arr); i++ {
for arr[i] > 0 {
if flag {
sum += (i - 10000)
}
flag = !flag
arr[i]--
}
}
return sum
}
func min(x, y int) int {
if x < y {
return x
}
return y
}
func arrayPairSum(nums []int) int {
sort.Ints(nums)
sum := 0
for i, j := 0, 1; j < len(nums); i, j = i+2, j+2 {
sum += min(nums[i], nums[j])
}
return sum
}
func arrayPairSum(nums []int) int {
sort.Ints(nums)
max_sum := 0
i := len(nums) - 1
for {
if i > 0 {
max_sum += nums[i-1]
i = i - 2
} else {
break
}
}
return max_sum
}
import "sort"
func min(x,y int) int{
if x < y {
return x
}
return y
}
func arrayPairSum(nums []int) int {
answer := 0
sort.Slice(nums, func(i,j int) bool { return nums[i] < nums[j] })
//fmt.Printf("%v\n", nums)
for i := 0; i < len(nums); i+=2 {
answer += min(nums[i], nums[i+1])
}
return answer
}
[Go] Two-pointer Technique - Scenario II (0) | 2022.04.12 |
---|---|
[Go] Array and string - Two Sum II - Input Array Is Sorted (0) | 2022.04.12 |
[Go] Array and string - Reverse String (0) | 2022.04.09 |
[GO] Array and string - Two-pointer Technique - Scenario I (0) | 2022.04.09 |
[Go] Array and string - Longest Common Prefix (0) | 2022.04.08 |
댓글 영역