Saturday, February 20, 2021

Leetcode Everyday: 1588. Sum of All Odd Length Subarrays. Easy

Solution for Sum of All Odd Length Subarrays:
public class Solution {
    public int SumOddLengthSubarrays(int[] arr) {
        int globalSum = 0;
           
        for (var odd = 1; odd <= arr.Length; odd += 2) {
            int count = 0;
            int sum = 0;
            for (; count < odd; ++count) {
                sum += arr[count];
            }
            // Log(sum);
            globalSum += sum;
            for (var i = count; i < arr.Length; ++i) {                
                sum += arr[i] - arr[i - odd];
                // Log(sum);
                globalSum += sum;
            }
            // Console.WriteLine();
        }
            
        return globalSum;
    }
    
    void Log(int n) {
          Console.Write("{0} ", n);   
    }
}
Output:
1 4 2 5 3 
7 11 10 
15 
There's a better solution than the above solution

No comments:

Post a Comment