classSolution: defkSum(self, nums: List[int], k: int) -> int: sum = 0 for i, x inenumerate(nums): if x >= 0: sum += x else: nums[i] = -x nums.sort() h = [(-sum, 0)] # 取负号变成最大堆 for _ inrange(k - 1): s, i = heappop(h) if i < len(nums): heappush(h, (s + nums[i], i + 1)) # 保留 nums[i-1] if i: heappush(h, (s + nums[i] - nums[i - 1], i + 1)) # 不保留 nums[i-1] return -h[0][0]
funckSum(nums []int, k int)int64 { n := len(nums) sum := 0 for i, x := range nums { if x >= 0 { sum += x } else { nums[i] = -x } } sort.Ints(nums) h := &hp{ {sum, 0} } for ; k > 1; k-- { p := heap.Pop(h).(pair) if p.i < n { heap.Push(h, pair{p.sum - nums[p.i], p.i + 1}) // 保留 nums[p.i-1] if p.i > 0 { heap.Push(h, pair{p.sum - nums[p.i] + nums[p.i-1], p.i + 1}) // 不保留 nums[p.i-1],把之前减去的加回来 } } } returnint64((*h)[0].sum) }
classSolution: defkSum(self, nums: List[int], k: int) -> int: sum = tot = 0 for i, x inenumerate(nums): if x >= 0: sum += x tot += x else: tot -= x nums[i] = -x nums.sort()
defcount(limit: int) -> int: cnt = 0 deff(i: int, s: int) -> None: nonlocal cnt if i == len(nums) or cnt >= k - 1or s + nums[i] > limit: return cnt += 1 f(i + 1, s + nums[i]) # 选 f(i + 1, s) # 不选 f(0, 0) return cnt returnsum - bisect_left(range(tot), k - 1, key=count)
classSolution { int[] nums; long limit; int k, cnt;
voidf(int i, long s) { if (i == nums.length || cnt >= k || s + nums[i] > limit) return; ++cnt; f(i + 1, s + nums[i]); // 选 f(i + 1, s); // 不选 }
publiclongkSum(int[] nums, int k) { longsum=0L, tot = 0L; for (vari=0; i < nums.length; i++) { if (nums[i] >= 0) sum += nums[i]; else nums[i] = -nums[i]; tot += nums[i]; } Arrays.sort(nums);
this.nums = nums; this.k = k - 1; longleft=0L, right = tot; while (left < right) { varmid= (left + right) / 2; this.limit = mid; cnt = 0; f(0, 0L); if (cnt >= k - 1) right = mid; else left = mid + 1; } return sum - left; } }
classSolution { public: longlongkSum(vector<int> &nums, int k){ long sum = 0L; for (int &x : nums) { if (x >= 0) sum += x; else x = -x; } sort(nums.begin(), nums.end());
--k; auto check = [&](long limit) -> bool { int cnt = 0; function<void(int, long)> f = [&](int i, long s) { if (i == nums.size() || cnt >= k || s + nums[i] > limit) return; ++cnt; f(i + 1, s + nums[i]); // 选 f(i + 1, s); // 不选 }; f(0, 0L); return cnt >= k; }; long left = 0L, right = accumulate(nums.begin(), nums.end(), 0L); while (left < right) { long mid = (left + right) / 2; if (check(mid)) right = mid; else left = mid + 1; } return sum - left; } };
funckSum(nums []int, k int)int64 { n := len(nums) sum, tot := 0, 0 for i, x := range nums { if x >= 0 { sum += x tot += x } else { tot -= x nums[i] = -x } } sort.Ints(nums)
k-- kthSmallest := sort.Search(tot, func(limit int)bool { cnt := 0 var f func(int, int) f = func(i, s int) { if i == n || cnt >= k || s+nums[i] > limit { return } cnt++ f(i+1, s+nums[i]) // 选 f(i+1, s) // 不选 } f(0, 0) return cnt >= k }) returnint64(sum - kthSmallest) }