Given a positive integer array num of size n, calculate and return the sum of all possible odd-length subarrays of num.
Example 1: Input: num[] = {1, 3, 2, 5, 6}; Output: 63
Explanation: List of Odd length subarrays:
[1] = 1
[3] = 3
[2] = 2
[5] = 5
[6] = 6
[1, 3, 2] = 6
[3, 2, 5] = 10
[2, 5, 6] = 13
[1, 3, 2, 5, 6] = 17
Sum of all odd length arrays: 1+3+2+5+6+6+10+13+17 = 63
Example 2: Input: num[] = {3, 5} Output: 8
Explanation:
List of Odd length subarrays:
[3] = 3
[5] = 5
Sum of all odd length arrays: 3+5 = 8
Approach 1: Brute Force Solution.
You can quickly get all possible subarrays by running two nested loops but the critical point of this problem is that you need to find only all odd-length subarrays.
You can use a generalized formula that if [(last_position_of_subarray - first_positon_ of _subarray)%2 == 0] then the length is odd else the length is even. You can then add the elements of that subarray to your answer.
C++ Solution Code:
/*C++ code to find sum of odd length subarray*/ #include<bits/stdc++.h> using namespace std; int sumOfOddSubarray(vector<int> &num){ int total = 0; for(int i = 0; i < num.size(); i++){ int sum = 0; for(int j = i; j < num.size(); j++){ sum += num[j]; if((j - i)%2 == 0) total += sum; } } return total; } int main(){ vector<int> num = {1, 3, 2, 5, 6}; int ans = sumOfOddSubarray(num); cout<<"Sum Of Odd Length subarrays: "<<ans; return 0; }
Sum Of Odd Length subarrays: 63
- Time Complexity: O(n^2)
- Space Complexity: O(1)
Approach 2: Using Math.
Given: [1, 4, 2, 5, 3]
Element Number of occurance Sum
ar[0] = 1 3 1x3 = 3
ar[1] = 4 4 4x4 = 16
ar[2] = 2 5 2x5 = 10
ar[3] = 5 4 5x4 = 20
ar[4] = 3 3 3x3 = 9
Total = 58
Explanation:
arr[2] = 2 present in 5 times(one time in row first,
three times in row second and one time in row third)
similarly we need to count for all elements.
/*C++ code to find sum of odd length subarray (Optimized)*/ #include<bits/stdc++.h> using namespace std; int sumOfOddSubarray(vector<int> &num){ int total = 0; int n = num.size(); for(int i = 0; i < n; i++){ total += ((i+1)*(n-i)+1)/2 * num[i]; } return total; } int main(){ vector<int> num = {1, 4, 2, 5, 3}; int ans = sumOfOddSubarray(num); cout<<"Sum Of Odd Length subarrays: "<<ans; return 0; }
Sum Of Odd Length subarrays: 58
- Time Complexity: O(n)
- Space Complexity: O(1)
No comments:
Post a Comment