Is my approach correct? can anyone have more optimised approach?
my code:
#include <iostream>
#include <vector>
using namespace std;
int main() {
int signal_size;
cin >> signal_size;
vector<int> signals(signal_size);
for (int i = 0; i < signal_size; ++i) {
cin >> signals[i];
}
int filter_A_sum = 0;
int filter_B_sum = 0;
int left = 0, right = signal_size - 1;
bool is_A_turn = true;
while (left <= right) {
if (is_A_turn) {
if (signals[left] > signals[right]) {
filter_A_sum += signals[left];
++left;
} else {
filter_A_sum += signals[right];
--right;
}
} else {
if (signals[left] > signals[right]) {
filter_B_sum += signals[left];
++left;
} else {
filter_B_sum += signals[right];
--right;
}
}
is_A_turn = !is_A_turn;
}
cout << filter_A_sum << endl;
return 0;
}
your approach is wrong as well as sample test 2 is also incorrect. we can do this problem using O(n^2) dp.
Guess what! You will get TLE.
See the range of N
i know but the best i could get is this. i still have to think about the optimal soln
thanks for the approach, if you figured out the optimal approach you are thinking about then do share.
yes, can you share the problem link
i don't have any link, it was asked in offline competition in my university.
This problem is solvable in $$$\Theta(N)$$$ via a greedy algorithm.
Let $$$(a, b, c)$$$ be three consecutive signals, satisfying $$$a, c \leq b$$$. You can replace it with a single signal with value $$$a - b + c$$$. The case where the largest signal is on the edge can be solved greedily.
Source: Algorithmic Engagements 2010, Termites.
can you elaborate it a bit more