#include "stdafx.h" #include <stdio.h> int _tmain(int argc, _TCHAR* argv[]) { int i, k = 0, count, count2, num1[100], num2[100]; printf("请输入数字个数,不超过50:"); scanf("%d", &count); count2 = count * 2; printf("请输入数字:"); for (i = 0; i<count; i++) { scanf("%d", &num1[i]); } for (i = 0; i<count2; i++) { if (i<count) num2[i] = num1[i]; else num2[i] = num1[i - count]; } int x = 0, maxsum = 0, nowsum = 0; for (i = x; i<count + x; i++) { nowsum = nowsum + num2[i]; if (nowsum>maxsum) { maxsum = nowsum; } else { maxsum = maxsum + 0; } if (i == count - 1 + x) { x++; if (x<count) { i = x - 1; nowsum = 0; } else break; } } printf("最大子数组的和:%d ", maxsum); return 0; }
设计思路:依照之前的思路这次的问题变成了如何把一个数组复制成两遍然后接起来(比如{1,2,3,4,5,6}变为{1,2,3,4,5,6,1,2,3,4,5})之后再用同样的一维数组求最大子数组的方法得到环形数组的最大子数组
于是就有了:
for (i = 0; i<count2; i++) { if (i<count) num2[i] = num1[i]; else num2[i] = num1[i - count]; }
先把数组变为2倍并把原数组内的原本放到数组2,再从头把原数组元素循环放入数组2,再用数组二实现求最大子数组
if (i == count - 1 + x) { x++; if (x<count) { i = x - 1; nowsum = 0; } else break; }
如果数组元素个数超过了数组长度就break,如果没有超过,就继续累加
这次编写代码难点就在于其中的循环的书写,赵宁很厉害想了出来,要向他学习