/** * 动态规划,计算出非环形数组各项的最大值 * 环形数据最大和子集考虑两种情况 * 该子集横跨与不横跨 * 横跨时,反向求解总和减去最小值 * * @param nums int整型一维数组 * @return int整型 */ export function maxSubarraySumCircular(nums: number[]): number { const maxList = Array(nums.length).fill(0); const minList = Array(nums.length).fill(0); let sum = 0; nums.forEach(( item,index )=>{ sum+=item; if((maxList[index -1] || 0 ) < 0){ maxList[index] = nums[index] } else{ maxList[index] = (maxList[index - 1] || 0) + nums[index]; } if((minList[index -1] || 0 ) > 0){ minList[index] = nums[index] } else{ minList[index] = (minList[index - 1] || 0) + nums[index]; } }) if(sum === Math.min(...minList)){ return Math.max(...maxList) } const max= sum - Math.min(...minList) return Math.max(max, ...maxList) }