Open carloscn opened 1 year ago
int32_t max_subsequence(int32_t *nums, size_t len, int32_t k, int32_t *out)
{
int32_t ret = 0;
UTILS_CHECK_PTR(nums);
UTILS_CHECK_PTR(out);
UTILS_CHECK_LEN(len);
UTILS_CHECK_CONDITION(k > len, -1, "k is oversize!");
for (size_t i = 0; i < len; i ++) {
for (size_t j = 0; j < len - i - 1; j ++) {
if (nums[j] < nums[j + 1]) {
utils_swap_int32(nums + j, nums + j + 1);
}
}
}
memcpy(out, nums, sizeof(int32_t) * k);
finish:
return ret;
}
Description
You are given an integer array nums and an integer k. You want to find a subsequence of nums of length k that has the largest sum.
Return any such subsequence as an integer array of length k.
A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
Example 1:
Input: nums = [2,1,3,3], k = 2 Output: [3,3] Explanation: The subsequence has the largest sum of 3 + 3 = 6.
Example 2:
Input: nums = [-1,-2,3,4], k = 3 Output: [-1,3,4] Explanation: The subsequence has the largest sum of -1 + 3 + 4 = 6.
Example 3:
Input: nums = [3,4,3,3], k = 2 Output: [3,4] Explanation: The subsequence has the largest sum of 3 + 4 = 7. Another possible subsequence is [4, 3].
Constraints:
1 <= nums.length <= 1000 -105 <= nums[i] <= 105 1 <= k <= nums.length