#include <iostream> #include <vector> #include <algorithm> using namespace std; /** Helpful links https://www.geeksforgeeks.org/longest-alternating-subsequence/ https://leetcode.com/problems/decrease-elements-to-make-array-zigzag/ https://en.wikipedia.org/wiki/Alternating_permutation */ int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n, count1 = 0, count2 = 0; cin >> n; vector<int> vect(n); for (int i = 0; i < n; i++) { cin >> vect[i]; } for (int i = 0; i < n - 1; i++) { if (i % 2 == 0 && vect[i] <= vect[i + 1]) { count1++; i++; continue; } if (i % 2 == 1 && vect[i] >= vect[i + 1]) { count1++; i++; continue; } } for (int i = 0; i < n - 1; i++) { if (i % 2 == 0 && vect[i] >= vect[i + 1]) { count2++; i++; continue; } if (i % 2 == 1 && vect[i] <= vect[i + 1]) { count2++; i++; continue; } } cout << min(count1, count2); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | #include <iostream> #include <vector> #include <algorithm> using namespace std; /** Helpful links https://www.geeksforgeeks.org/longest-alternating-subsequence/ https://leetcode.com/problems/decrease-elements-to-make-array-zigzag/ https://en.wikipedia.org/wiki/Alternating_permutation */ int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n, count1 = 0, count2 = 0; cin >> n; vector<int> vect(n); for (int i = 0; i < n; i++) { cin >> vect[i]; } for (int i = 0; i < n - 1; i++) { if (i % 2 == 0 && vect[i] <= vect[i + 1]) { count1++; i++; continue; } if (i % 2 == 1 && vect[i] >= vect[i + 1]) { count1++; i++; continue; } } for (int i = 0; i < n - 1; i++) { if (i % 2 == 0 && vect[i] >= vect[i + 1]) { count2++; i++; continue; } if (i % 2 == 1 && vect[i] <= vect[i + 1]) { count2++; i++; continue; } } cout << min(count1, count2); } |