連結串列基本操作
阿新 • • 發佈:2021-06-29
題目來源:53. 最大子序和
給定一個整數陣列nums
,找到一個具有最大和的連續子陣列(子陣列最少包含一個元素),返回其最大和。
方法一:動態規劃
/** * @param {number[]} nums * @return {number} */ var maxSubArray = function(nums) { let pre = 0; let max = -Infinity; for(let num of nums){ pre = Math.max(pre+num , num); max = Math.max(max, pre); }return max; };
方法二:字首和
/** * @param {number[]} nums * @return {number} */ var maxSubArray = function(nums) { let n = nums.length; let sums = new Array(n).fill(0); let max = -Infinity; let i = 1; for(let num of nums){ sums[i] = sums[i-1] + num; i += 1; } for(let i = 0;i<n;i++){for(let j=i+1;j<=n;j++){ let dp = sums[j] - sums[i]; max = Math.max(max, dp); } } return max; };
示例 1:
輸入:nums = [-2,1,-3,4,-1,2,1,-5,4] 輸出:6 解釋:連續子陣列[4,-1,2,1] 的和最大,為6 。
示例 2:
輸入:nums = [1] 輸出:1
示例 3:
輸入:nums = [0] 輸出:0
示例 4:
輸入:nums = [-1] 輸出:-1
示例 5:
輸入:nums = [-100000] 輸出:-100000
提示:
1 <= nums.length <= 3 * 104
-105<= nums[i] <= 105