|
| 1 | +// Link - https://leetcode.com/problems/sum-of-all-odd-length-subarrays/ |
| 2 | + |
| 3 | +/* |
| 4 | +1588. Sum of All Odd Length Subarrays |
| 5 | + |
| 6 | +Given an array of positive integers arr, calculate the sum of all possible odd-length subarrays. |
| 7 | + |
| 8 | +A subarray is a contiguous subsequence of the array. |
| 9 | + |
| 10 | +Return the sum of all odd-length subarrays of arr. |
| 11 | + |
| 12 | + |
| 13 | + |
| 14 | +Example 1: |
| 15 | + |
| 16 | +Input: arr = [1,4,2,5,3] |
| 17 | +Output: 58 |
| 18 | +Explanation: The odd-length subarrays of arr and their sums are: |
| 19 | +[1] = 1 |
| 20 | +[4] = 4 |
| 21 | +[2] = 2 |
| 22 | +[5] = 5 |
| 23 | +[3] = 3 |
| 24 | +[1,4,2] = 7 |
| 25 | +[4,2,5] = 11 |
| 26 | +[2,5,3] = 10 |
| 27 | +[1,4,2,5,3] = 15 |
| 28 | +If we add all these together we get 1 +たす 4 +たす 2 +たす 5 +たす 3 +たす 7 +たす 11 +たす 10 +たす 15 =わ 58 |
| 29 | +Example 2: |
| 30 | + |
| 31 | +Input: arr = [1,2] |
| 32 | +Output: 3 |
| 33 | +Explanation: There are only 2 subarrays of odd length, [1] and [2]. Their sum is 3. |
| 34 | +Example 3: |
| 35 | + |
| 36 | +Input: arr = [10,11,12] |
| 37 | +Output: 66 |
| 38 | + |
| 39 | + |
| 40 | +Constraints: |
| 41 | + |
| 42 | +1 <= arr.length <= 100 |
| 43 | +1 <= arr[i] <= 1000 |
| 44 | +*/ |
| 45 | + |
| 46 | +// Naive Approach |
| 47 | + |
| 48 | +class Solution { |
| 49 | +public: |
| 50 | + int sumOddLengthSubarrays(vector<int>& arr) { |
| 51 | + |
| 52 | + int odd = 1; |
| 53 | + int sum = 0, result = 0; |
| 54 | + for(int i = 0; i < arr.size(); i++){ |
| 55 | + for(int j = i; j < arr.size(); j++){ |
| 56 | + sum += arr[j]; |
| 57 | + if(odd % 2 == 1){ |
| 58 | + result += sum; |
| 59 | + } |
| 60 | + odd++; |
| 61 | + } |
| 62 | + sum = 0; |
| 63 | + } |
| 64 | + return result; |
| 65 | + } |
| 66 | +}; |
| 67 | + |
| 68 | +// Better Approach |
| 69 | + |
| 70 | +class Solution { |
| 71 | +public: |
| 72 | + int sumOddLengthSubarrays(vector<int>& arr) { |
| 73 | + int len = arr.size(), k, sum = 0; |
| 74 | + for(int i = 0; i < len; i++){ |
| 75 | + k = (len - i) * (i + 1); |
| 76 | + if(k % 2 == 0) k /= 2; |
| 77 | + else k = (k / 2) + 1; |
| 78 | + sum += arr[i] * k; |
| 79 | + } |
| 80 | + return sum; |
| 81 | + } |
| 82 | +}; |
0 commit comments