Leetcode--53. 最大子序和

package soloproject;

/**
 * 最大子序和
 * 
 * @author GGGXXC
 *
 */
public class MaxSubseqSum {
    public static void main(String[] args) {
        int[] nums = new int[] { -2, 1, -3, 4, -1, 2, 1, -5, 4 };

        System.out.println(maxSubArray(nums));
    }

    /**
     * 最大子序和核心算法
     * 
     * @param nums 传入的数组
     * @return 返回最大和
     */
    public static int maxSubArray(int[] nums) {

        /**
         * 初始值设置为数组第一项,保存的为当前最大子序和
         */
        int allSum = nums[0];

        /**
         * 当数组中出现负值后,重新开始的新子序和
         */
        int curSum = 0;
        for (int n : nums) {
            if (curSum < 0) {
                curSum = 0;
            }

            /**
             * 加上新数字之后的新子序和和历史最大子序和进行比较
             */
            curSum += n;
            allSum = Math.max(allSum, curSum);

        }
        return allSum;
    }
}

 

posted @ 2020-05-10 23:15  路漫漫兮其修远  阅读(85)  评论(0编辑  收藏  举报