C Language Enhancement (3) Calculate the largest sum of sub-arrays, array

Source: Internet
Author: User

C Language Enhancement (3) Calculate the largest sum of sub-arrays, array

In the previous article, I answered the question of finding the minimum element in the stack. In this article, I will talk about how to find the maximum sum of the array Neutron array.

You can master this question.

  • How to create an array based on user input
  • How to find and maximize a continuous number substring in a series of numbers
  • How to discover potential problems and use this rule to design algorithms to solve problems



Ideas

  • The sum of continuous numbers must be the largest, indicating that the numbers on both sides are definitely not negative. Otherwise, it cannot be the largest.
  • A negative number is allowed in the continuous number sequence, provided that the positive number in the first section of the negative number must be greater than this negative number. Otherwise, after the two are offset, the number will decrease.
Algorithm
Traverse Arrays
When a positive number is encountered, it is accumulated constantly. When the first positive number is encountered, the subscript must be recorded. When a negative number is encountered, the subscript must be recorded, use the array between this subscript minus 1 and the subscript of the positive number of the previous record as a possible largest array, and compare it with the previous possible largest array. If it becomes larger, it will replace it!
Determine the relationship between the accumulated value and the negative number.
If the cumulative value is greater than negative, continue accumulating
If the accumulated value is less than or equal to a negative number, discard the negative number and move forward. The accumulated value is cleared.

Source code
<Span style = "font-size: 14px;" >#include <stdio. h> # include <stdlib. h> # include <iostream> # include <vector> # include <sstream> using namespace std;/** enter an integer array with positive or negative numbers in the array. One or more consecutive integers in the array form a sub-array. Each sub-array has a sum. Returns the maximum value of the sum of all sub-arrays. The time complexity is O (n ). For example, the input array is 1,-2, 3, 10,-4, 7, 2,-5, and the maximum sub-array is 3, 10,-4, 7, 2, so the output is the sum of 18 of the Child array. The thought is that the continuous number addition must be the largest, indicating that the numbers on both sides are definitely not allowed to have negative numbers in the negative continuous number sequence, provided that the positive number in front of the negative number is greater than this negative algorithm: when traversing an array, we encounter positive numbers and accumulate them constantly. When we encounter the first positive number, we need to record negative numbers and subscripts, use the array between this subscript minus 1 and the subscript of the positive number of the previous record as a possible largest array, and compare it with the previous possible largest array. If it becomes larger, it will replace it! Determine the relationship between the accumulated value and the negative number. If the accumulated value is greater than the negative number, continue to accumulate. If the accumulated value is less than or equal to a negative number, discard the negative number, move forward, and clear the accumulated value */void main () {// create an array vector <int> oriArray based on user input; int n = 0, count = 0; string str; bool endFlag = true; while (endFlag) {cout <"Enter the" <count <"array element, enter e to end the input" <endl; cin> str; if (str = "e") {endFlag = false;} else {stringstream (str)> n; oriArray. push_back (n); count ++ ;}} cout <"the input array is" <endl; for (int I = 0; I <oriArray. size (); I ++) {cout <oriArray [I] <"" ;}// calculate the maximum sub-array/** add: Accumulate value ori: the starting angle of the accumulate value max: the largest and maxOri: the largest and the starting angle of the subarray maxEnd: maximum and subarray end badge */int add = 0, ori = 0, max = 0, maxOri = 0, maxEnd = 0; bool firstPos = true; // traverse for (int I = 0; I <oriArray. size (); I ++) {// if (oriArray [I]> = 0) {add + = oriArray [I]; // accumulate if (firstPos) {// the first positive number must be recorded as the subscript ori = I; firstPos = false;} else {// a negative number // It is the largest and most likely to be compared with the previous one, if it increases, it will replace! If (add> max) {max = add; maxOri = ori; maxEnd = I-1;}/** determine the relationship between the cumulative value and the negative number. if the cumulative value is greater than the negative number, continue accumulating if the accumulated value is less than or equal to a negative number, discard this negative number, move forward, and clear the accumulated value */if (oriArray [I] + add> 0) {add + = oriArray [I];} else {add = 0; if (I + 1 <oriArray. size () ori = I + 1 ;}}// after jumping out of the loop, Judge again if (add> max) {max = add; maxOri = ori; maxEnd = oriArray. size ()-1 ;}cout <endl; cout <maxOri <"<maxEnd <endl; cout <"the maximum value of the maximum sub-array is" <max <endl; cout <"the maximum sub-array is" <endl; for (int I = maxOri; I >= maxOri & I <= maxEnd; I ++) {cout <oriArray [I] <"" ;}system ("pause ");} </span>

Running Diagram



The key to this question is to find that the two ends of the largest and sub-arrays cannot be negative.
After that, I found a similar answer on the Internet and found that some great gods gave me a better solution. Share it here.
Train of Thought 2: Number of current faces, after adding up, after B <0,
Assign B a value again and set it to the next element, B = a [I].
When B> sum, sum = B is updated;
If B <sum, sum retains the original value and is not updated.

Source code 2:
<Span style = "font-size: 14px;" >#include <stdio. h> # include <stdlib. h> # include <iostream> # include <sstream> using namespace std;/** enter an integer array, and the array contains both positive and negative numbers. One or more consecutive integers in the array form a sub-array. Each sub-array has a sum. Returns the maximum value of the sum of all sub-arrays. The time complexity is O (n ). For example, the input array is 1,-2, 3, 10,-4, 7, 2,-5, and the maximum sub-array is 3, 10,-4, 7, 2, so the output is the sum of 18 of the Child array. The current number of ideas, after adding up, B <0, re-assign B to the next element, B = a [I]. When B> sum, sum = B is updated. If B <sum, sum is kept as the original value. */int maxSum (int * a, int n) is not updated) {int sum = 0; int B = 0; for (int I = 0; I <n; I ++) {if (B <= 0) // The preceding number. After adding up, B <0b = a [I]; // B returns the value of elseb + = a [I]; // The preceding number, after adding up, B> = 0 and continue accumulating if (sum <B) sum = B; // B> sum, update sum = B} return sum;} void main () {int a [10] = {1,-, 3,-, 7,-, 1 }; cout <"maximum sum of sub-arrays" <maxSum (a, 10) <endl; system ("pause") ;}</span>

Solution 2 is more concise than solution 1, because it not only realizes that the number at both ends cannot be a negative number, but also as long as the number of sub-arrays in the string is less than 0, it cannot be a part of the largest and sub-arrays.

Each problem has its own law. The process of designing an algorithm is the process of discovering and utilizing the law.

It's like playing badminton. If I find that my opponent can play the short ball as long as I go back to High distance, I will rush to the network to prepare for the fight next time.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.