1588. Sum of All Odd Length Subarrays

int sum = 0;
        int n = arr.size();
        for(int i=0;i<n;i++)
        {
            // number of subarray starts with arr[i] 
            int start_i = n-i;
            // number of subarray ends with arr[i] 
            int end_i = i+1;
            // number of subarray contains arr[i] 
            int total_sub = start_i*end_i;
            
            // number of odd length subarray is ceil of total subarray/2 which is the contribution of arr[i]
            // number of contribution in odd length subarray * arr[i] value
            // ceil 返回大于或等于 x 的最小的整数值
            // cout<<(int)ceil(total_sub/2.0)/2<<endl;
            cout<<arr[i] * (int)ceil(total_sub/2.0)<<endl;
            sum+= arr[i] * (int)ceil(total_sub/2.0);
        }
        
        return sum;
Input: arr = [1,4,2,5,3]
Output: 58
Explanation: The odd-length subarrays of arr and their sums are:
[1] = 1
[4] = 4
[2] = 2
[5] = 5
[3] = 3
[1,4,2] = 7
[4,2,5] = 11
[2,5,3] = 10
[1,4,2,5,3] = 15
If we add all these together we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58

猜你喜欢

转载自blog.csdn.net/Vpn_zc/article/details/115057096