Find Combinations For Game Scoring - Coderust - Hacking The Coding Interview
Find Combinations For Game Scoring - Coderust - Hacking The Coding Interview
• Description
• Hints
• Try it yourself
• Solution
• Runtime complexity
• Memory complexity
Description #
Find an efficient algorithm to find the maximum sum of a subsequence in
an array so that no consecutive elements are part of this subsequence.
1 6 10 14 -5 -1 2 -1 3
max sum = 25
https://www.educative.io/courses/coderust-hacking-the-coding-interview/j2J5P 1/6
02/11/2020 Find Combinations for Game Scoring - Coderust: Hacking the Coding Interview
1 -1 6 -4 2 2
max sum = 9
Note that we did not pick 10 and 14 at indices 2 and 3 because they are
adjacent. It is a requirement that we have to pick nonadjacent elements
only.
Hints #
Think along the lines of the Fibonacci sequence.
Try it yourself #
C++ Java Python JS Ruby
int find_max_sum_nonadjacent(vector<int>& a) {
// TODO: Write - Your - Code
return -1;
}
Solution #
Runtime complexity #
The runtime complexity of this solution is linear, O(n).
Memory complexity #
The memory complexity of this solution is linear, O(n).
https://www.educative.io/courses/coderust-hacking-the-coding-interview/j2J5P 2/6
02/11/2020 Find Combinations for Game Scoring - Coderust: Hacking the Coding Interview
Initial setup
1 of 7
https://www.educative.io/courses/coderust-hacking-the-coding-interview/j2J5P 3/6
02/11/2020 Find Combinations for Game Scoring - Coderust: Hacking the Coding Interview
int find_max_sum_nonadjacent(vector<int>& a) {
if (a.size() == 0) {
return 0;
}
if (a.size() == 1) {
return a[0];
}
result[0] = a[0];
for (int i = 1; i < a.size(); i++) {
if ((i - 2) >= 0) {
result[i] = max(result[i], a[i] + result[i-2]);
}
}
return result[a.size() - 1];
}
int main() {
vector<int> v = {1, -1, 6, -4, 2, 2};
int sum = find_max_sum_nonadjacent(v);
cout << "Max sum of nonadjacent subsequence: " << sum;
}
0 1 2 3
Initial State
0 0 0 1
Results Array
https://www.educative.io/courses/coderust-hacking-the-coding-interview/j2J5P 4/6
02/11/2020 Find Combinations for Game Scoring - Coderust: Hacking the Coding Interview
1 of 6
return result[3];
}
int main() {
cout << "Number of ways score 5 can be reached = " << scoring_options(5); //10
}
Back Next
Mark as Completed
https://www.educative.io/courses/coderust-hacking-the-coding-interview/j2J5P 5/6
02/11/2020 Find Combinations for Game Scoring - Coderust: Hacking the Coding Interview
23% completed, meet the criteria and claim your course certi cate!
Buy Certificate
Ask a Question
Report
(https://discuss.educative.io/tag/ nd-combinations-for-game-scoring__dynamic-
an Issue
programming__coderust-hacking-the-coding-interview)
https://www.educative.io/courses/coderust-hacking-the-coding-interview/j2J5P 6/6