博客
关于我
求最大连续子序列和——解法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 子进程 Popen 与 Pyinstaller
查看>>
Python 子进程 Popen.communicate() 等价于 Popen.stdout.read()?
查看>>
Python 子进程 Popen:为什么会出现“ls *.txt“?不行?
查看>>
Python 子进程参数
查看>>
python 字典 key 和value 互换
查看>>
Python 字典 vs If 语句速度
查看>>
python 字典sorted自定义排序,按照key or value排序
查看>>
python 字典和列表区别_元组列表和字典的主要区别是什么?
查看>>
python 字符串中特定字符替换,截取
查看>>
Python 字符串总结
查看>>
python 字符串显示中文_Python字符串开头的b"、u"、r"与中文乱码
查看>>
Python 字符串的几种拼装方式
查看>>
python 存入数据库bigint_python基础_MySQL的bigint类型
查看>>
python 学习 面向对象编程
查看>>
Python 学习小结
查看>>
Python 学习日记第三篇 -- 字典
查看>>
Python 学习笔记(一)Data type
查看>>
python 安装 easy_install 和 pip 流程
查看>>
python 安装echarts
查看>>
python 安装opencv及问题解决
查看>>