알고리즘/leetcode

1588. Sum of All Odd Length Subarrays

유이얼 2022. 9. 13. 03:35
class Solution {
public:
    int sumOddLengthSubarrays(vector<int>& arr) {
        int n = arr.size();
        int ans = 0;
        for (int i = 0; i < n; ++i) {
            int k = (i + 1) * (n - i);  // total_left * total_right
            k = ((i+2)/2)*((n-i+1)/2) + ((i+1)/2)*((n-i)/2);
            //cout << k << '\n';
            ans += k*arr[i];
        }
        return ans;
    }
};