Advertisement
ANTAR_NANDI

Sum of All Odd Length Subarrays

Apr 5th, 2025 (edited)
296
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.34 KB | Software | 0 0
  1.     vector<int> arr = {1,4,2,5,3};
  2.     int size = arr.size();
  3.     int sum = 0;
  4.     vector<int> prefix(size+1);
  5.     for(int i =1;i<=size;i++)
  6.     {
  7.         prefix[i] = prefix[i-1] + arr[i-1];
  8.     }
  9.     for(int i =1;i<=size;i++)
  10.     {
  11.         for(int j=i;j<=size;j++)
  12.         {
  13.             if(((j-i) + 1) %2 == 1)
  14.             {
  15.                 sum += (prefix[j] - prefix[i-1]);
  16.             }
  17.         }
  18.     }
  19.     return sum;
Tags: leetcode
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement