LintCode 41. 最大子數組

給定一個整數數組,找到一個具有最大和的子數組,返回其最大和。

public class Solution {
   /**
    * @param nums: A list of integers
    * @return: A integer indicate the sum of max subarray
    */
   public int maxSubArray(int[] nums) {
      // write your code here
      int max = Integer.MIN_VALUE, tmp = 0;
      for (int i = 0; i < nums.length; i++) {
         if (tmp < 0) {
            tmp = nums[i];
         } else {
            tmp += nums[i];
         }
         if (tmp > max) {
            max = tmp;
         }
      }
      return max;
   }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章