Question: Find and the largest sub-array from an array. The array may have negative numbers.
Idea:Perform the following steps to list all the situations and make a comparison record!
- Compile a method for calculating the sum within a certain range of arrays.
- Traverse all the situations in sequence and record the maximum value.
The C ++ implementation is as follows:
// ================================================ ==================================================================== // Name: maxsubarray. CPP // Author: Jue // version: // copyright: Your copyright notice // Description: Hello world in C ++, ANSI-style // ========================================== ========================================================== = # include <iostream> using namespace STD; class mydata {public: int startindex; int endindex; int maxdata ;}; int getsum (INT datas [], int start, int end) {int sum = 0; for (INT I = start; I <= end; I ++) {sum + = datas [I];} return sum;} mydata * findmaxsubarray (INT datas [], int length) {mydata * Data = new mydata; For (INT I = 0; I <length; I ++) {for (Int J = I; j <length; j ++) {int sum = getsum (datas, I, j); If (I = 0 & J = 0) | (sum> data-> maxdata) {data-> maxdata = sum; data-> startindex = I; data-> endindex = J ;}} return data ;} int main () {int datas [] = {1,-2,-3}; mydata * Data = findmaxsubarray (datas, 3 ); cout <"max =" <data-> maxdata <"Start:" <data-> startindex <"end:" <data-> endindex; return 0 ;}