Link Search Menu Expand Document

1588. Sum of All Odd Length Subarrays

Solution Code

C

int sumOddLengthSubarrays(int* arr, int arrSize){
    int ans = 0;
    
    for (int len = 1; len <= arrSize; len += 2) {
        int sum = 0;
        
        for (int i = 0; i < len; i++) {
            sum += arr[i];
        }
        
        ans += sum;
        
        for (int i = len; i < arrSize; i++) {
            sum += (arr[i] - arr[i - len]);
            ans += sum;
        }
    }
        
    return ans;
}

C#

public class Solution {
    public int SumOddLengthSubarrays(int[] arr) {
        int ans = 0, n = arr.Length;
        
        for (int len = 1; len <= n; len += 2) {
            int sum = 0;
            for (int i = 0; i < len; i++) {
                sum += arr[i];
            }
            ans += sum;
            for (int i = len; i < n; i++) {
                sum += (arr[i] - arr[i - len]);
                ans += sum;
            }
        }
        
        return ans;
    }
}

C++

class Solution {
public:
    int sumOddLengthSubarrays(vector<int>& arr) {
        int ans = 0, n = arr.size();
        
        for (int len = 1; len <= n; len += 2) {
            int sum = 0;
            for (int i = 0; i < len; i++) {
                sum += arr[i];
            }
            ans += sum;
            for (int i = len; i < n; i++) {
                sum += (arr[i] - arr[i - len]);
                ans += sum;
            }
        }
        
        return ans;
    }
};

Java

class Solution {
    public int sumOddLengthSubarrays(int[] arr) {
       int ans = 0, n = arr.length;
        
        for (int len = 1; len <= n; len += 2) {
            int sum = 0;
            for (int i = 0; i < len; i++) {
                sum += arr[i];
            }
            ans += sum;
            for (int i = len; i < n; i++) {
                sum += (arr[i] - arr[i - len]);
                ans += sum;
            }
        }
        
        return ans; 
    }
}

© 2023. All rights reserved.