博客
关于我
求最大连续子序列和——解法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 基于 wordcloud + jieba + matplotlib 生成词云
查看>>
python 基于detectron或mask_rcnn的mask遮罩区域进行图片截取
查看>>
Python编程:Tkinter图形界面设计(2)
查看>>
Python 基础 - Day 5 Learning Note - 模块 之 标准库:time (1)
查看>>
Python 基础一
查看>>
python 基础操作知识整理总结
查看>>
Python 基础知识点整理与分享,期盼你的交流!
查看>>
python 基础第七篇
查看>>
Python编程:Tkinter图形界面设计(1)
查看>>
Python 基础语法:None
查看>>
Python 基础语法:基本数据类型(一)
查看>>
python编程读取写入excel_Python读取txt内容写入xls格式excel中的方法
查看>>
Python 基础语法:基本数据类型(字典)
查看>>
Python 基础语法:基本数据类型(字符串)
查看>>
Python 基础语法:基本数据类型(集合)
查看>>
Python编程的终极十大工具
查看>>
python 堆排序
查看>>
python编程方式之一-函数式编程
查看>>
python 复习计划
查看>>
Python 多处理 apply_async 永远不会在 Windows 7 上返回结果
查看>>