Two problems to solve similar problems are solved to the sequence given sequence to meet certain mathematical characteristics (maximum and / product of the maximum), even though not required the output sequence.
The key phrase is to pay attention to: containing at least one numberso there is at least a given sequence elements, which can also inspire us as special treatment.
A thought: $ sums [j] $ is the largest sub-segment before the sequence j elements and sub-problems to solve as, the $ sum [n] $, compared with the answer. However, how to use the $ sums [1, 2, ..., j-1] $ to $ sums [j] $ solve it? Obviously need to know the maximum field and former j-element sub-segment start and end positions, solving the problem of sub-state transition is clearly more complicated.
Put it another thought. Two ideas: $ sums [j] $ is the maximum sub-segment with the first end of the j-th element of a child subsegment and problem solving, $ max_ {1 leq j leq n} (sums [j]) $ is the entire and the largest sub-segment sequences. Through $ sums [j-1] $ $ current element and the nums [j] can be calculated at $ j-th element is the largest sub-segment and ending $ sums [j] $, 状态转移方程as follows: $$ sums [j +. 1 ] = begin {cases} nums [ j + 1] sums [j] lt 0 cr sums [j] + nums [j + 1] others end {cases} $$
In order to obtain largestSumsequences corresponding to the variable that we can startIdxrecord the j-th element to the end ( endIdxstarting position) and the maximum sub-segment corresponding sub-sequence, $ nums [startIdx, ..., endIdx] $ is the corresponding sequence; Further, considering the current state and the previous state only relevant , it can be used instead of array variables, save memory, while avoiding acquire The largest sum of the whole arrayrepeated cycles of time.
classSolution { public: intmaxSubArray(vector<int>& nums){ int SizeofNums = nums.size(); if(SizeofNums == 1) { return nums[0]; } // largest sum for the subarray ending with current element int curSum = nums[0]; // largest sum of subarray for the whole array int largestSum = curSum; // subarray[startIdx, endIdx] with largest sum for the whole array int startIdx = 0, endIdx = 0 ; for ( int i = 1 ; i <SizeofNums; i ++) { if (Cursor < 0 ) { cursor = nums [i]; startIdx = i; } Else { cursor speed + = nums [i]; } If (runner> largestSum) { largestSum = speed; endIdx = i; } } Return largestSum; } };
The problem solving process is substantially similar to the previous question, but the key problem to be solved is: the state transition, that is, how (max product to the j-th element is the end of the sub-segment) is calculated based on answers on a sub-problem the results of the current sub-problems.