【问题标题】:Prefix sum time complexity前缀和时间复杂度
【发布时间】:2014-01-28 18:37:13
【问题描述】:

我正在阅读this,最后一部分的练习。

我是时间复杂度的新手。

第一个解决方案说机器人会在一个方向移动p 次,然后在另一个方向移动m - p,对于p0m,对我来说这是:

sums = []
for left in 0..m
  sums[left] = 0
  for right in 0..(m-left)
    sums[left] += A[k - left + right] || 0
    A[k - left + right] = 0

A 是输入数组,k 是初始位置,即给定常量。

据我了解,复杂性是:

O(m + m+(m-1)+(m-2)+...+3+2+1)
  |   -----------------------
  |               |
  because        because the inner loop
  first loop

O(m + (m*(m+1))/2)
O(m + (m*(m+1))/2)
O(m^2) ?

我的错误是什么?

这个问题的解决方案指出复杂性是O(n*m),你能解释一下为什么吗?

【问题讨论】:

    标签: complexity-theory time-complexity


    【解决方案1】:
    the goal is to calculate the maximum sum that the robot can collect in m moves.
    

    这样,我理解算法将类似于:

    max=0;
    for i in 1..n
        for j in 1..m
            sum+=A[i]
        end loop;
        if sum>max then 
            max=sum;
        end if;
        sum=0;
    end loop;
    

    这是一个 O(n*m) 问题(如果我理解正确的话)

    【讨论】:

    • 对不起,我忘了提到k 我更新了问题,机器人从k 的位置开始并移动了m 次,我无法理解为什么涉及n,你能解释一下?
    猜你喜欢
    • 1970-01-01
    • 2018-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-14
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多