Created
December 15, 2014 15:54
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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