Returns the sum of the largest child arrays in an integer array (improved code) and an integer array.

Source: Internet
Author: User
Tags sca

Returns the sum of the largest child arrays in an integer array (improved code) and an integer array.

1. Design Philosophy

(1) create a one-dimensional array a [] to store data based on the length and content of the array entered by the user.

(2) then several variables are defined. sum is used for summation, max is and maximum, and num is the array length.

(3) Start the for loop. sum is initialized to 0, and max is initialized to a [0]. The loop content is sum + = a [I]. If sum is greater than max, the sum value is assigned to max. If sum is smaller than 0, the sum = 0 is defined. Until the loop ends, get the sum of the largest sub-array.

2. Source Code

// Return the maximum sub-array and maximum package ketang of a one-dimensional integer array; import java. util. *; public class ArrayMax {public static void main (String [] args) {extends sca = new evaluate (System. in); System. out. println ("Number of input integer arrays"); int num = sca. nextInt (); int a []; a = new int [num]; System. out. println ("Number of input arrays"); int I; for (I = 0; I <num; I ++) {a [I] = sca. nextInt () ;}int sum = 0, max = a [0]; for (I = 0; I <num; I ++) {sum + = a [I]; if (max <sum) {max = sum;} if (sum <0) {sum = 0 ;}} System. out. println ("maximum sub-array and sum" + max) ;}} The Main Code

3. Results

4. Programming Summary

After listening to the design ideas, I felt that his method was simpler than my previous method. Then I wrote this code by referring to his method.

Related Article

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.