博客
关于我
求最大连续子序列和——解法1 – 暴力出奇迹||解法2 – 分治
阅读量:526 次
发布时间:2019-03-07

本文共 1305 字,大约阅读时间需要 4 分钟。

最大子数组问题

问题背景:给定一个整数数组,找到其中所有可能的连续子序列中和最大的那一个。

暴力解法

暴力方法是穷举所有可能的连续子序列,计算它们的和,并取最大值。这种方法的时间复杂度为O(n 3),主要是因为三个嵌套循环。虽然简单,但在数据量较大时效率很低。

public int maxSubArray(int[] nums) {    if (nums == null || nums.length == 0) return 0;    int max = Integer.MIN_VALUE;    for (int begin = 0; begin < nums.length; begin++) {        for (int end = begin; end < nums.length; end++) {            int sum = 0;            for (int i = begin; i <= end; i++) {                sum += nums[i];            }            max = Math.max(max, sum);        }    }    return max;}

优点:逻辑简单,直观易懂。

优化思路

在暴力解法的基础上,可以通过将前面已经计算过的子序列和缓存起来,从而将时间复杂度优化到O(n 2)。通过这种方式可以减少重复计算,但仍然不如更优的时间复杂度比如O(n log n)

public int maxSubArray(int[] nums) {    if (nums == null || nums.length == 0) return 0;    int max = Integer.MIN_VALUE;    for (int begin = 0; begin < nums.length; begin++) {        int sum = 0;        for (int end = begin; end < nums.length; end++) {            sum += nums[end];            max = Math.max(max, sum);        }    }    return max;}

优点:实现了在同一层循环中逐步累加,节省了一部分计算量,但仍然不是最优解。

分治法

通过将问题分解成更小的子问题,采用递归的方式解决。这种方法的时间复杂度为O(n log n),是当前最优解。

public int maxSubArray(int[] nums) {    if (nums == null || nums.length == 0) return 0;    return maxSubArray(nums, 0, nums.length);}

millones总结ovalZYConsumingcontent千千Balanced 优化后的内容将在多个地方出现,以避免 恶意 垃圾链接。

转载地址:http://loznz.baihongyu.com/

你可能感兴趣的文章
Python中DrissionPage的详细解析与实战
查看>>
python中enumerate、变量类型转换
查看>>
python中execute是啥_python – 为什么“c.execute(…)”打破循环?
查看>>
python中exit和break区别_Python中exit()和sys.exit()之间的区别
查看>>
python中h5的用法
查看>>
python中http协议编程_HTTP编程
查看>>
python中import os_Python:相对导入与绝对导入(import)、os.path、__file__
查看>>
Python中set.discard和set.remove方法之间的运行时差异?
查看>>
python中yield的用法详解——最简单,最清晰的解释
查看>>
python中‘set.intersection()‘的算法是什么?
查看>>
Python中一个图形中的多个绘图
查看>>
python中一个好的持久同步队列
查看>>
Python中不准确的对数
查看>>
python中什么是实例方法_在Python中创建实例方法对象的不同方法
查看>>
Python中使用cutecharts实现简单的手绘风格的图表
查看>>
python中使用dxfgrabber,解析dxf文件信息生成obj文件
查看>>
Python中使用ncmbot玩转网易云音乐
查看>>
Python中使用PIL快速实现二值图
查看>>
Python中使用PIL快速实现灰度图
查看>>
Python中使用pip install ncmbot时各种错误解决办法
查看>>