Sum of All Subarrays | 3 Approaches Explained | Java | AlgoXploration

แชร์
ฝัง
  • เผยแพร่เมื่อ 11 ม.ค. 2025

ความคิดเห็น • 1

  • @AlgoXploration
    @AlgoXploration  หลายเดือนก่อน +1

    public int sumOfSubarrays(int[] arr) {
    // Initialize a variable 'sum' to store the total sum of all subarray sums.
    int sum = 0;
    // Get the length of the input array 'arr'.
    int n = arr.length;
    // Loop through each element of the array.
    for (int i = 0; i < n; i++) {
    // Calculate how many subarrays include the element at index 'i'.
    // The element at index 'i' appears in (i + 1) subarrays starting from index 0 to i,
    // and it also appears in (n - i) subarrays ending at index i to (n - 1).
    // Therefore, the total number of subarrays that include arr[i] is (i + 1) * (n - i).
    int c = (i + 1) * (n - i);
    // Multiply the element arr[i] by the count 'c' and add it to the total sum.
    // This ensures that arr[i] contributes to the sum of all subarrays where it appears.
    sum += (arr[i] * c);
    }
    // Return the total sum of all subarrays.
    return sum;
    }