数组
一、题目:(感谢
http://blog.youkuaiyun.com/v_JULY_v 提供的题目)
二、题目分析:
三、代码:
求子数组的最大和
输入一个整形数组,数组里有正数也有负数。
数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。
求所有子数组的和的最大值。要求时间复杂度为O(n)。
例如输入的数组为1, -2, 3, 10, -4, 7, 2, -5,和最大的子数组为3, 10, -4, 7, 2,
因此输出为该子数组的和18。
二、题目分析:
(1)看到题目的第一反应就是一个while循环再在里面添加一个for循环,遍历所有可能的组合,输出最大值。这样的时间复杂度为O(n^2),不符合题目的要求。
(2)把数组依次遍历相加,如果相加结果少于0,就清空;大于0就继续。最终得到最大和。
三、代码:
(1)
//时间复杂度为O(n^2) const int total = 11; //数组元素个数 int index = 0; //当前数组指标 int sum = 0; //单个总和 int s_max = - (1 << 31); //最大总和 (int型的范围为:-2^31 -- 2^31) int a[total] = {-5,10,-8,-3,2,9,-5,4,5,6,-11}; while(index < total) { sum = 0; for(int i=index;i<total;i++) { sum += a[i]; s_max = (sum > s_max ? sum : s_max); } index++; } cout<<s_max;
(2)
//时间复杂度为O(n) const int total = 11; int a[total] = {-5,10,-8,36,2,9,-5,4,5,6,-11}; int sum = 0; int s_max = - (1 << 31); int index = 0; while (index < total) { sum += a[index++]; if (sum > s_max) s_max = sum; if (sum < 0) sum = 0; } cout<<s_max;