题目:输入一个整型数组,数组里有正数也有负数。数组中一个或连续的多个整数组成一个子数组。求元素和值最大的那个子数组的和值。
C#实现:
public static int FindGreatestSumOfSubArray(int[] pData) { if (pData.Length <= 0) return -1; int nCurSum = 0; int nGreatestSum = 0; for (int i = 0; i < pData.Length; i++) { if (nCurSum <= 0) nCurSum = pData[i]; else nCurSum += pData[i]; if(nCurSum > nGreatestSum) nGreatestSum = nCurSum; } return nGreatestSum; }
Java实现:
public static int findGreatestSumOfSubArray(int[] pData) { if (pData.length <= 0) return -1; int nCurSum = 0; int nGreatestSum = 0; for (int i = 0; i < pData.length; i++) { if (nCurSum <= 0) nCurSum = pData[i]; else nCurSum += pData[i]; if(nCurSum > nGreatestSum) nGreatestSum = nCurSum; } return nGreatestSum; }
Python实现:
def find_greatest_sum_of_sub_array(pData): """ 连续子数组的最大和 输入一个整型数组,数组里有正数也有负数。数组中一个或连续的多个整数组成一个子数组。 求元素和值最大的那个子数组的和值 :param pData: :return: """ if len(pData) <= 0: return nCurSum = 0 nGreatestSum = 0 for item in pData: if nCurSum <= 0: nCurSum = item else: nCurSum += item if nCurSum > nGreatestSum: nGreatestSum = nCurSum return nGreatestSum