数组的所有子数组总和

本文讨论了一种解决如何在O(n)时间复杂度内计算数组所有子数组总和的方法,避免了使用三重循环的简单暴力求解。通过分析每个元素在子数组中的出现情况,分为两种情况考虑:元素作为子数组起点和作为其他子数组的一部分。通过计算每种情况下的子数组数量,得出总和的公式,并提供了C++的实现。
摘要由CSDN通过智能技术生成

Problem statement:

问题陈述:

Find sum of all subarray sums out of an array.

查找数组中所有子数组总和的和。

Example:

例:

    Input array: 
    [1, 2, 3, 4]
    
    Output:
    50

Solution:

解:

Of course, there exists an easy solution where we can use three for loops with time complexity (O (n3)). The outer loop and intermediate loop are to iterate through all subarrays and the innermost one is to compute the sum. But here, we are not going to discuss this simple brute-force solution. Rather we will discuss an efficient way to minimize the time complexity.

当然,存在一个简单的解决方案,其中我们可以使用三个具有时间复杂度(O(n3))的 for循环。 外循环和中间循环将遍历所有子数组,而最内层将计算总和。 但是在这里,我们将不讨论这种简单的暴力解决方案。 相反,我们将讨论一种最小化时间复杂度的有效方法。

Let's look at an example first,

我们先来看一个例子

    Array = [1, 2, 3, 4]
    Sub-arrays are
    [1] =1
    [2] =2
    [3] =3
    [4] =4
    [1, 2] =1+2=3
    [2, 3] =2+3= 5


    [3, 4] =3+4 =7
    [1, 2, 3] = 1+2+3= 6
    [2, 3, 4] = 2+3+4= 9
    [1, 2, 3, 4] = 1+2+3+4 = 10
    Total sum= 50

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值