fork download
  1. //{ Driver Code Starts
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5.  
  6. // } Driver Code Ends
  7.  
  8. /*You are required to complete this function*/
  9.  
  10. class Solution {
  11. public:
  12. int maxLen(vector<int>& arr) {
  13. // code here
  14. int n=arr.size();
  15. int sum=0;
  16. int longest=0;
  17. map<int,int>mp;
  18. mp[0]=-1;
  19. for(int i=0;i<n;i++){
  20. sum+=arr[i];
  21. if(mp.find(sum)!=mp.end()){
  22. longest=max(longest,i-mp[sum]);
  23. }else{
  24. mp[sum]=i;
  25. }
  26. }
  27. return longest;
  28. }
  29. };
  30.  
  31.  
  32.  
  33. //{ Driver Code Starts.
  34.  
  35. int main() {
  36. int t;
  37. cin >> t;
  38. cin.ignore(); // to ignore the newline after the integer input
  39. while (t--) {
  40. int n;
  41. vector<int> a;
  42. string input;
  43.  
  44. // Input format: first number n followed by the array elements
  45. getline(cin, input);
  46. stringstream ss(input);
  47. int num;
  48. while (ss >> num)
  49. a.push_back(num);
  50.  
  51. Solution obj;
  52. cout << obj.maxLen(a) << endl;
  53. cout << "~\n";
  54. }
  55.  
  56. return 0;
  57. }
  58.  
  59. // } Driver Code Ends
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
Standard output is empty