/*================================================================*\ 题目:求子数组的最大和 输入一个整形数组,数组里有正数也有负数。数组中连续的一个或多个整数组成一个子数组,每一个子数组都有一个和。求全部子数组的和的最大值。ios
要求时间复杂度为 O(n) 。数组
例如输入的数组为 1, -2, 3, 10, -4, 7, 2, -5 ,和最大的子数组为 3, 10, -4, 7, 2 ,所以输出为该子数组的和18 。 \*================================================================*/spa
分析:code
遍历数组时,get
#include <iostream> using namespace std; int get_max_sum(int a[],int len){ #保存当前元素和最大值 int a_max[len]; #记录最大和 int max=a[0]; a_max[0]=a[0]; for(int i=1;i<len;i++){ a_max[i]=a[i]>a_max[i-1]+a[i]?a[i]:a_max[i-1]+a[i]; max=a_max[i]>max?a_max[i]:max; } return max; } int main(){ int a[10]={-1,2,10,-4,7,2,-5}; int max=get_max_sum(a,10); cout<<"max:"<<max<<endl; return 0; }
补充C++语法(都快忘了)编译器
/* *C++多行注释 */ //包含了头文件 <iostream> #include <iostream> //告诉编译器使用 std 命名空间。 using namespace std; // main() 是程序开始执行的地方 int main() { cout << "Hello World"; // 输出 Hello World return 0; }