思路:

  1. 创建一个长度为N的结果列表result,初始值都为0。
  2. 从第二天开始遍历股票价格列表stockPrices,将当前价格与前一天的价格进行比较。
  3. 如果当前价格大于前一天的价格,则说明股票价格上涨,将对应位置的结果列表result的值设为1。
  4. 如果当前价格小于等于前一天的价格,则说明股票价格没有上涨,将对应位置的结果列表result的值加1。
  5. 返回结果列表result。

时间复杂度分析: 遍历股票价格列表需要O(N)的时间,其中N为股票价格列表的长度。

空间复杂度分析: 需要一个长度为N的结果列表result,空间复杂度为O(N)。

关键代码如下所示:

def stock_prices(stockPrices): N = len(stockPrices) result = [0] * N for i in range(1, N): if stockPrices[i] > stockPrices[i-1]: result[i] = 1 else: result[i] = result[i-1] + 1 return result

测试样例

stockPrices = [33, 34, 14, 12, 16] print(stock_prices(stockPrices)


原文地址: https://www.cveoy.top/t/topic/iZYz 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录