Skip to content

Instantly share code, notes, and snippets.

@sturgle
Created December 15, 2014 15:54
Show Gist options
  • Save sturgle/f11dad0bb0107de25137 to your computer and use it in GitHub Desktop.
Save sturgle/f11dad0bb0107de25137 to your computer and use it in GitHub Desktop.
find the k sub-sequence of the array to make the sum largest, the numbers are from 0-9
#include <iostream>
#include <vector>
#include <cassert>
using namespace std;
int kSum(vector<int> arr, int k) {
assert(k <= arr.size());
vector<int> count(10);
for (int i = 0; i < arr.size(); i++) {
count[arr[i]]++;
}
int sum = 0;
for (int i = 9; i >= 0; i--) {
if (count[i] >= k) {
sum += i * k;
return sum;
} else {
sum += i * count[i];
k -= count[i];
}
}
}
int main() {
int a[17] = {5, 1, 7, 5, 6, 8, 0, 6, 8, 4, 9, 1, 2, 3, 1, 8, 7};
vector<int> arr;
arr.assign(a, a + 17);
//int last = 0;
for (int i = 0; i <= 17; i++) {
int r = kSum(arr, i);
//cout << "diff: " << r - last << endl;
//last = r;
cout << "KSUM " << i << " : " << r << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment