title: Array queries give wrong answer
body: <p>I have a problem and I have no idea how to start, here it is:</p>
  <blockquote>
  <p>You are given a permutation of 1,2,...,n.
  You will be given q queries, each query being one of 2 types:</p>
  <p>Type 1: swap elements at positions i and j<br>
  Type 2: given a position i, print the length of the longest subarray containing the ith element such that the sum of its elements doesn't exceed n</p>
  <h3>Input</h3>
  <p>The first line contains 2 integers n and q (1≤n,q≤105).</p>
  <p>The next line contains the n integers of the permutation p1,…,pn (1≤pi≤n).</p>
  <p>The next q lines contain queries in the format:</p>
  <p>Type 1: 1 i j (1≤i,j≤n)<br />
  Type 2: 2 i (1≤i≤n)</p>
  <h3>Output</h3>
  <p>For each query of type 2, print the required answer.</p>
  </blockquote>
  <p>Here is my code so far, but it gives me the wrong answer on the last few cases:</p>
  <pre><code>#include &lt;iostream&gt;
  #include &lt;algorithm&gt;
  
  long long atMostSum(int arr[], int n, int k, int a)
  {
      int sum = arr[a];
      int cnt = 1, maxcnt = 1;
  
      for (int i = 0; i &lt; n; i++) {
  
          if ((sum + arr[i]) &lt;= k) {
              sum += arr[i];
              cnt++;
          }
  
          else if(sum!=0)
          {
              sum = sum - arr[i - cnt] + arr[i];
          }
  
          maxcnt = std::max(cnt, maxcnt);
      }
      return maxcnt - 1;
  }
  
  int main(void) {
      int n, q;
      std::cin &gt;&gt; n &gt;&gt; q;
      int p[n];
      for(int i = 0; i &lt; n ; i++) {
          std::cin &gt;&gt; p[i];
      }
      for (int i = 0; i &lt; n; i ++) {
          int a;
          std::cin &gt;&gt; a;
          if (a == 2) {
              int m;
              std::cin &gt;&gt; m;
              std::cout &lt;&lt; atMostSum(p, n, n, m) &lt;&lt; &quot;\n&quot;;
          } else {
              int l, f;
              std::cin &gt;&gt; l &gt;&gt; f;
              int temp;
              temp = p[l];
              p[l] = p[f];
              p[f] = temp;
          }
      }
  }
  </code></pre>
  <h3>Sample Input</h3>
  <pre><code>3 3
  1 2 3
  2 1
  2 2
  2 3
  </code></pre>
  <h3>Sample Output</h3>
  <pre><code>2
  2
  1
  </code></pre>