算法是爲求解一個問題須要遵循的、被清楚地指定的簡單的指令的集合。對於一個問題,一旦給定某種算法而且肯定是正確的,那麼重要的一步是肯定該算法將須要多少諸如時間和空間的問題,也就是要分析該算法的時間複雜度和空間複雜度,時間複雜度低和空間複雜度低就表明該算法是好的,但咱們要努力找到最優的算法。下面來看看最大子序列和問題的最優求解算法,用php實現了php
function maxSubSum($arr) { $maxSum = $sum = $leftIndex = $rightIndex = 0; $flag = false; foreach ($arr as $key=>$value) { $sum += $value; if ($sum > $maxSum) { $maxSum = $sum; if($flag) { $leftIndex = $key; $flag = false; } $rightIndex = $key; } if($sum <0) { $sum = 0; $maxSum = 0; $flag = true; } } return array_slice($arr,$leftIndex,($rightIndex - $leftIndex)+1); }
再來看看python實現python
#!/usr/bin/python def findMaxSubArray( inputList ): if ( len( inputList ) == 0 ): return inputList middle = len( inputList ) / 2 leftSum,rightSum,crossingSum,tmpSum = 0,0,0,0 leftIndex,rightIndex = 0,len(inputList) leftSum = sum(inputList[0:middle]) rightSum = sum(inputList[middle+1:]) tmpIndex = middle -1 while ( tmpIndex >0): tmpSum +=inputList[tmpIndex] if(tmpSum > leftSum): leftIndex = tmpIndex break; tmpIndex = tmpIndex - 1 tmpIndex = middle+1 while (tmpIndex < len( inputList )): tmpSum += inputList[tmpIndex] if( tmpSum > rightSum ): rightIndex = tmpIndex break; tmpIndex = tmpIndex + 1 return inputList[leftIndex:rightIndex] if __name__ == '__main__': inputList = [-1,-2,-4,-8,-3,-10,-13,-56,-33,-2,-4,-45,-55,-12,-3] #inputList = [1,2,-4,8,4,0,-10,3,56,33,2,4,-45,55,0,-12,3] print findMaxSubArray ( inputList )
最後我想請教一個問題,爲何求餘運算耗費很大,知道原理的請解答一下。算法