Given an integer number a [] {a [0],..., a [n])}, find the continuous substring {a [x]), a [x + 1],..., a [y]}, so that the sum is the largest, where, 0
Given an integer number a [] = {a [0],..., a [n])}, find the continuous substring {a [x]), a [x + 1],..., a [y]}, so that the sum is the largest, where 0 <= x <= y <= n. The time complexity is O (n ).
Solution:
- And the largest substring must end with an element in array a. Therefore, we calculate the current and largest substrings for each element as the end of the current substring respectively, then compare all the calculated substrings and the biggest one is the solution.
- Calculate the largest substring ending with element a (I + 1). assume that the sum of the substrings ending with a (I) is L [I], sum [I], when sum [I] + a [I + 1]> a [I + 1], then L [I + 1] is L [I] plus a [I + 1], sum [I + 1] = sum [I] + a [I + 1]; otherwise, L [I + 1] is a [I], sum [I + 1] = a [I + 1]; why? Note that "continuous" means that the substring ending with a [I + 1] must contain a [I + 1]. the largest substring L [I + 1] can only be a [I + 1] or L [I] plus a [I + 1]. Obviously, sum [I] + a [I + 1]> a [I + 1] does not take a [I + 1], but takes L [I] and a [I + 1], otherwise, a [I + 1] is obtained.
The code is as follows:
Struct SubMax // The largest and largest substring {int start; // The substring start position int end; // The substring end position int sum; // And }; subMax maxsub (int a [], int size) {int ** sub = new int * [size]; // array of maximum substring information ending with all elements, A total of size one-dimensional arrays. // each one-dimensional array contains three elements. the 0 subscript substring is the starting position, and the 1 subscript is the ending position, 2 subscript and for (int k = 0; k
A [I + 1]) {sub [I + 1] [0] = sub [I] [0]; sub [I + 1] [1] = I + 1; sub [I + 1] [2] = sub [I] [2] + a [I + 1];} else {sub [I + 1] [0] = I + 1; sub [I + 1] [1] = I + 1; sub [I + 1] [2] = a [I + 1] ;}} int max_sub = 0; int maxsubsum = 0; for (int j = 0; j
Maxsubsum) {maxsubsum = sub [j] [2]; max_sub = j ;}} SubMax s; s. start = sub [max_sub] [0]; s. end = sub [max_sub] [1]; s. sum = sub [max_sub] [2]; for (int m = 0; m
Address of this article: http://www.nowamagic.net/librarys/veda/detail/331,welcome.