Leetcode Problem 1588. Sum of All Odd Length Subarrays

1588. Sum of All Odd Length Subarrays

Leetcode Solutions

Approach: Check the occurrence of each index

  1. Initialize answer as 0.
  2. Iterate over the array arr using index i.
  3. Calculate the number of odd and even subarrays to the left and right of arr[i]:
    • odd_left = (i / 2) + 1
    • odd_right = ((n - i - 1) / 2) + 1
    • even_left = (i + 1) / 2
    • even_right = (n - i) / 2
  4. Calculate the occurrence of arr[i] in odd-length subarrays as odd_left * odd_right + even_left * even_right.
  5. Multiply the occurrence by arr[i] and add it to answer.
  6. Return answer after the loop.
UML Thumbnail

Approach: Two Loops

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...