求解数组中连续一段子数组和的最大数列的乘积
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <time.h> | |
// 问题: | |
// 求解数组中连续一段子数组和的最大数列的乘积。 | |
// | |
// 解答:特殊情况,全是负数的时候需要处理 | |
// 先应该判断是否数字大于0,大于0则进行乘积运算 | |
// 然后将运算的结果跟上次运算的结果进行比较, | |
// 如果大于上次结果就保存,直到遍历结束.期间增加 | |
// 一个标记记录是否全部是否负数的情况. | |
// | |
int max_mul(int* a, int n) | |
{ | |
int maxSum = 0; | |
int sum = 1, i = 0, temp = a[0], all_neg = 1; // 这里的temp和all_neg用于处理全部负数的情况 | |
for (; i < n; i++) { | |
if (a[i] > 0) { | |
sum *= a[i]; | |
all_neg = 0; | |
} else { | |
if (a[i] > temp) | |
temp = a[i]; | |
sum = 1; | |
} | |
if (sum > maxSum) | |
maxSum = sum; | |
} | |
if (all_neg) | |
return temp; | |
else | |
return maxSum; | |
} | |
int shuffle(int *a, int n) | |
{ | |
int i = 0; | |
if (rand() % 2) { | |
for (; i < n; i++) { | |
a[i] = rand() % 20; | |
if ((rand() % 2) == 0) | |
a[i] = -a[i]; | |
if (a[i] == 0) | |
a[i] = rand() % 30; | |
} | |
return 0; | |
} else { | |
for (i = 0; i < n; i++) | |
a[i] = -(rand() % 20); | |
return 1; | |
} | |
} | |
void print_array(int *a, int n) | |
{ | |
for (int i = 0; i < n; i++) { | |
printf("%d ", a[i]); | |
} | |
printf("\n"); | |
} | |
int main(int argc, char **argv) | |
{ | |
srand(time(NULL)); | |
int a[10]; | |
int len = sizeof(a) / sizeof(a[0]); | |
shuffle(a, len); | |
print_array(a, len); | |
printf("sum %d\n", max_mul(a, len)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment