博客
关于我
求最大连续子序列和——解法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/

你可能感兴趣的文章
sum(a.YYSR) over (partition by a.hy_dm) 不需要像group by那样需要分组函数。方便。
查看>>
ORCHARD 是什么?
查看>>
Struts2中使用Session的两种方法
查看>>
Stream API:filter、map和flatMap 的用法
查看>>
STM32工作笔记0032---编写跑马灯实验---寄存器版本
查看>>
Static--用法介绍
查看>>
ssm旅游信息管理系统的设计与实现bus56(程序+开题)
查看>>
order by rand()
查看>>
SSM(Spring+SpringMvc+Mybatis)整合开发笔记
查看>>
ViewHolder的改进写法
查看>>
Orderer节点启动报错解决方案:Not bootstrapping because of 3 existing channels
查看>>
org.apache.axis2.AxisFault: org.apache.axis2.databinding.ADBException: Unexpected subelement profile
查看>>
sql查询中 查询字段数据类型 int 与 String 出现问题
查看>>
org.apache.commons.beanutils.BasicDynaBean cannot be cast to ...
查看>>
org.apache.dubbo.common.serialize.SerializationException: com.alibaba.fastjson2.JSONException: not s
查看>>
sqlserver学习笔记(三)—— 为数据库添加新的用户
查看>>
org.apache.http.conn.HttpHostConnectException: Connection to refused
查看>>
org.apache.ibatis.binding.BindingException: Invalid bound statement错误一例
查看>>
org.apache.ibatis.exceptions.PersistenceException:
查看>>
org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
查看>>