最大字段和问题
来源:互联网 发布:协同过滤算法流程图 编辑:程序博客网 时间:2024/06/01 10:09
本人大学生一枚,最近做老师布置的作业:求一组整数的最大子段和 (例如{2,-1,4,-5,6,-3}) 以下是本人的作业代码:
public class Test_001 { public static void main(String[] args)throws Exception{ int array[] = {2,-1,4,-5,6,-3};//这里直接定义了数组,也可以输入 int count,i,j; int max = 0; count = 6; for(i=0;i<=count;i++) for(j=i;j<count;j++) { int sum=0; sum= sum + array[j]; if(sum>max){ max=sum; } } System.out.println("数组的最大子段和胃"+max ); } }
本来觉得自己的代码还不错,比其他同学的时间复杂度好。但是却没想到可以用动态规划优化。
static int maxSubsegment(int[] a,int n) { int temp = 0,maxn = 0,k=1; int start,end; for(int i = 0 ; i < n ;i++) { temp+=a[i]; if(temp > maxn) { maxn = temp;start = k ;end = i; } if(temp < 0) { temp = 0;k = i+1; } } return maxn; }
小结:发现之前都是依葫芦画瓢的敲代码,并没有思考过为什么,导致经常有想当然就写了。然而方法不只有一种,不要固化自己的想法。
阅读全文
0 0
- 最大字段和问题
- 最大字段和问题
- 最大字段和问题
- 最大字段和问题
- 最大字段和问题
- 最大字段和问题
- 最大字段和问题
- dp 最大字段和 问题
- 背包问题I--最大字段和
- 动态规划:最大字段和问题
- 动态规划之最大字段和问题
- 最大字段求和问题
- 数组问题之一维最大字段和问题<Java实现>
- 最大字段和问题 难点分析和C++实现9
- hdu1231 最大字段和
- 求最大字段和
- 最大字段和
- 最大子字段和
- Spring mvc Ambiguous mapping found. Cannot map controller bean method
- Android Binder Analysis(4)
- 选择排序、冒泡排序算法
- WaitForMultipleObjects
- 对Java线程池的学习
- 最大字段和问题
- Git详解
- POJ 1315 Don't Get Rooked 笔记
- 剑指offer 面试题6 重建二叉树
- java 单个或多个文件上传
- 成员变量和局部变量
- iOS学习笔记--图片上传
- 快乐司机
- JQuery 操作Cookie