Continuous subarray LC-1186 can be deleted and a maximum number of

problem:

Given an array, find all its successive sub-arrays, and is the largest number, note that these sub-arrays, you can choose to delete up to a number.

 

Ideas:

The subject, in fact, prove safety offer face questions in 42: A variant of the largest and continuous sub-array. The difference is that, you find the sub-arrays, you can also choose to delete one.

And offer to prove safety in the way, by re-iterate, the current is calculated and the maximum, and recorded for each position and a maximum, the return value at the end position of the element.

And we need to deal with here, sub-arrays, and after removing the piece will not be larger than the original.

So here we add a loop through the array from the tail, and calculate the maximum at the beginning of the current element position.

So, in the calculation of all locations and from the end of the maximum, as well as from the biggest and began. The largest and, from that position before a comparison we just need to pull out a certain element (assuming that position i) after (i - 1) and the end of the maximum plus a (i + 1) from the start position and the maximum, will be able to know the maximum and sub-array.

 

Code:

 1 class Solution {
 2 public:
 3     int maximumSum(vector<int>& arr) {
 4         int n = arr.size();
 5         vector<int> end_here(n);
 6         vector<int> start_here(n);
 7         int max_sum = arr[0];
 8         end_here[0] = arr[0];
 9         for (int i = 1; i < n; i++) {
10             end_here[i] = max(arr[i], end_here[i - 1] + arr[i]);
11             max_sum = max(max_sum, end_here[i]);
12         }
13         start_here[n - 1] = arr[n - 1];
14         for (int i = n - 2; i >= 0; i--) {
15             start_here[i] = max(arr[i], start_here[i + 1] + arr[i]);
16         }
17         for (int i = 1; i < n - 1; i++) {
18             max_sum = max(max_sum, end_here[i - 1] + start_here[i + 1]);
19         }
20         return max_sum;
21     }
22 };

 

Guess you like

Origin www.cnblogs.com/leo-lzj/p/11486145.html