Sum of All Odd Length Subarrays

As a Systems Engineer at Tata Consultancy Services, I deliver exceptional software products for mobile and web platforms, using agile methodologies and robust quality maintenance. I am experienced in performance testing, automation testing, API testing, and manual testing, with various tools and technologies such as Jmeter, Azure LoadTest, Selenium, Java, OOPS, Maven, TestNG, and Postman.
I have successfully developed and executed detailed test plans, test cases, and scripts for Android and web applications, ensuring high-quality standards and user satisfaction. I have also demonstrated my proficiency in manual REST API testing with Postman, as well as in end-to-end performance and automation testing using Jmeter and selenium with Java, TestNG and Maven. Additionally, I have utilized Azure DevOps for bug tracking and issue management.
Given an array of positive integers arr, return the sum of all possible odd-length subarrays of arr.
A subarray is a contiguous subsequence of the array.
LeetCode Problem - 1588
class Solution {
public int sumOddLengthSubarrays(int[] arr) {
int result = 0; // Initialize a variable to store the sum of all odd-length subarrays
// Loop through each element in the array
for(int i = 0; i < arr.length; i++) {
result += arr[i]; // Add the current element to the result
result += checkOddLengthSum(i, arr); // Add the sum of all odd-length subarrays starting at index i
}
return result; // Return the total sum of all odd-length subarrays
}
// Helper method to calculate the sum of all odd-length subarrays starting at a given index
public int checkOddLengthSum(int start, int[] array) {
int answer = 0; // Initialize a variable to store the sum of odd-length subarrays
List<Integer> al = new ArrayList<>(); // Initialize a list to store the current subarray
al.add(array[start]); // Add the starting element to the list
// Loop through the remaining elements in the array starting from the next index
for(int j = start + 1; j < array.length; j++) {
al.add(array[j]); // Add the current element to the list
// If the size of the list is odd
if(al.size() % 2 != 0) {
int temp = 0; // Initialize a temporary variable to store the sum of the current subarray
// Loop through each element in the current subarray and calculate the sum
for(int e : al) {
temp += e;
}
answer += temp; // Add the sum of the current subarray to the answer
}
}
return answer; // Return the sum of all odd-length subarrays starting at the given index
}
}




