---
# System prepended metadata

title: 1588. Sum of All Odd Length Subarrays
tags: [C++, LeetCode-Easy]

---

# 1588. Sum of All Odd Length Subarrays
Difficulty: Easy

## Solution

```cpp=
/**
*** Author: R-CO
*** E-mail: daniel1820kobe@gmail.com
*** Date: 2020-10-23
**/
#include <cstdlib>
#include <iostream>
using std::cout;
using std::endl;
#include <vector>
using std::vector;

struct TestCaseStruct {
  vector<int> input;
  int expected_output;
};

class Solution {
 public:
  int sumOddLengthSubarrays(vector<int>& arr) {
    int sum = 0;
    const auto kArrSize = arr.size();
    auto subarr_size = static_cast<size_t>(1);

    while (subarr_size <= kArrSize) {
      auto index_begin_pos = static_cast<size_t>(0);
      auto index_end_pos = index_begin_pos + subarr_size - 1;
      while (index_end_pos < kArrSize) {
        for (auto i = index_begin_pos; i <= index_end_pos; ++i) {
          sum += arr[i];
        }

        ++index_begin_pos;
        ++index_end_pos;
      }

      subarr_size += 2;
    }

    return sum;
  }
};

int main(int argc, char* argv[]) {
  vector<TestCaseStruct> test_cases = {
      {{1, 4, 2, 5, 3}, 58}, {{1, 2}, 3}, {{10, 11, 12}, 66}};

  Solution solution;
  for (size_t i = 0; i < test_cases.size(); ++i) {
    auto& test_case = test_cases[i];
    if (solution.sumOddLengthSubarrays(test_case.input) ==
        test_case.expected_output) {
      cout << "Test case [" << i << "] is PASS" << endl;
    } else {
      cout << "Test case [" << i << "] is FAILED" << endl;
    }
  }
  return EXIT_SUCCESS;
}

```

## Result

Success
Details 
Runtime: 8 ms, faster than 42.18% of C++ online submissions for Sum of All Odd Length Subarrays.
Memory Usage: 8.7 MB, less than 64.60% of C++ online submissions for Sum of All Odd Length Subarrays.

###### tags: `LeetCode-Easy` `C++`
