最大子数组之和(线性时间复杂度,C语言实现)

来源:互联网 发布:2017年淘宝销量排行榜 编辑:程序博客网 时间:2024/05/21 10:53
#include <stdio.h>#include <stdlib.h>#define NUM 7void max_subarray(int *);int main(){int A[NUM] = {-2,5,3,-6,4,-8,6};for (int i = 0; i < NUM; i++){printf("%d  ", A[i]);}printf("\n");max_subarray(A);return 0;}void max_subarray(int A[]){int max = -30;//当数组值全为负值时,max的初始化值必须小于其最大值。int temp = -1;//初始化值小于0。int s = 0, e  = 0, p = 0;//s记录开始,e记录结束位置。(记录的是数组下标)for (int j = 0; j < NUM; j++){if (temp < 0){temp = 0;p = j;}temp += A[j];if (temp > max){max = temp;s = p;e = j;}}printf("%d %d %d\n", s, e,  max);}

0 0
原创粉丝点击