題目:輸入一個整型數組,數組裏有正數也有負數。數組中一個或連續的多個整數組成一個子數組。求元素和值最大的那個子數組的和值。java
C#實現:
python
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實現:
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; }
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