fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main() {
  5. // Longest subarray whose sum is not divisible by x
  6. int n;
  7. cin >> n;
  8. vector<int> arr(n);
  9. for(int i = 0; i < n; i++) {
  10. cin >> arr[i];
  11. }
  12.  
  13. int x;
  14. cin >> x;
  15.  
  16. int prefix = 0;
  17. int j = -1;
  18. int ans = INT_MIN;
  19.  
  20. for(int i = 0; i < n; i++) {
  21. prefix += arr[i];
  22. if(prefix % x != 0) {
  23. ans = max(ans, i + 1);
  24. } else {
  25. if(j != -1) {
  26. ans = max(ans, i - j);
  27. } else {
  28. j = i;
  29. }
  30. }
  31. }
  32.  
  33. if(ans == INT_MIN) {
  34. cout << -1 << endl;
  35. } else {
  36. cout << ans << endl;
  37. }
  38.  
  39. return 0;
  40. }
  41.  
Success #stdin #stdout 0.01s 5288KB
stdin
5
3 1 4 2 2
3
stdout
4