ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

How do I find the largest continuous sum in a list? Kadane's Algorithm is the answer.

Updated on August 27, 2015

The Problem

You are presented with an unordered list of numbers. What is the largest sum in this list you can find by only adding contiguous numbers, meaning no gap in the series?

Analysis

This problem is a simple problem typically given to computer science students in their early years. We are given an unordered list of data, which means we must scan each element at least once. The best complexity we can possible achieve will be O(n). Is this possible?

If we know how many elements are in the list, we could add each element and find the list sum. Would this be the largest sum in the list? This would be true only if all the elements in the list are a positive value. Any negative values would bring the sum down. Does this mean we need to eliminate any negative values? No, if considering a list such as { 5, -1, 10, -11 }. In this example, the answer would be adding elements one through three, which would result in 14.

What we know so far:

1. We need to find a sum using contiguous numbers in an unordered list that is larger than the sum of any other combination of contiguous numbers.

2. The list is unordered, thus each element needs to be scanned at least once.

3. Just adding every element in the list is not correct when negative values are entered.

4. Eliminating negative numbers is not correct if surrounded by larger positive values.

Joseph Kadane of Carnegie Mellon University
Joseph Kadane of Carnegie Mellon University

The Algorithm

This problem was solved by an algorithm designed by Joseph Kadane of Carnegie Mellon University. It runs with a time complexity of O(n), which is the best possible scenario considering the problem constraints.

In order to solve the problem, we need to consider each element. We can easily see what the sum is ending at this element's position by adding the element to the previous sum. The issue is where is the starting point? We already determined that negative numbers can be included if they are surrounded by larger positive values. If adding a negative number to the sum results in a sum larger than the neighboring element, we can keep that element in our contiguous list, otherwise we set the neighboring element as a new starting point. Doing this, we can end up having to keep track of several contiguous sums, but we only care about keeping track of one at a time and what the maximum value is. Therefore, at a minimum, we need to keep track of two different values. What is the sum of the current contiguous list, and what is the maximum sum of all contiguous lists?

The algorithm:

1. Establish a variable to keep track of the current contiguous list. We will refer to this variable as sum.

2. Establish a variable to keep track of the maximum contiguous list. We will refer to this variable as maxSum.

3. Set sum and maxSum equal to the first element of the list.

4. Iterate through each element from the second element to the final element. Return to this step for each iteration.

5. Add the nth element to sum, and compare the result to sum. If the new result is larger than the current element, set sum to the new result. Otherwise, set sum to the current element.

6. If the value of sum is larger than the value of maxSum, set maxSum to sum.

7. Return to step 4 for the next element. If there are no final elements, return max as the answer.

Examples

Let's perform the algorithm on the list: { 5, -1, 10, -11 }

First element: 5
Value of sum: 5
Value of max: 5

Second element: -1
Value of (sum + n): 4
Value of sum: 4
Value of max: 5

Third element: 10
Value of (sum + n): 14
Value of sum: 14
Value of max: 14

Fourth element: -11
Value of (sum + n): 3
Value of sum: 3
Value of max: 14

Return value: 14

As we can see, the algorithm returns the correct result from the small list of items we analyzed at the beginning of this problem. Let's try another, more complex list: { 2, -4, -6, 9, 8, -11, 10, 2, -20 }

First element: 2
Value of sum: 2
Value of max: 2

Second element: -4
Value of (sum + n): -2
Value of sum: -2
Value of max: 2

Third element: -6
Value of (sum + n): -8
Value of sum: -6 (-6 is larger than -8, sum is set to -6)
Value of max: 2

Fourth element: 9
Value of (sum + n): 3
Value of sum: 9 (9 is larger than 3, sum is set to 9)
Value of max: 9

Fifth element: 8
Value of (sum + n): 17
Value of sum: 17
Value of max: 17

Sixth element: -11
Value of (sum + n): 6
Value of sum: 6
Value of max: 17

Seventh element: 10
Value of (sum + n): 16
Value of sum: 16
Value of max: 17

Eighth element: 2
Value of (sum + n): 18
Value of sum: 18
Value of max: 18

Ninth element: -20
Value of (sum + n): -2
Value of sum: -2
Value of max: 18

The answer given is 18, which is the sum of the fourth element through the eighth element in the list.

The Code: C++

Here is an example of a single function that runs Kadane's Algorithm in C++. The only parameter passed to the function is the number of elements that need to be input. The algorithm then follows the steps of the algorithm while scanning each element once. If no elements are provided, then -1 is returned as an error. It is assumed that there are no input errors that will conflict with the variable types. It is also assumed that there will be no overflow.

#include <iostream>
#include <cmath>

using namespace std;

int LargestContiguousSum(int numElements)
{
     if (numElements < 1)
	return -1;
     
     int num;

     cin >> num;
     
     int sum = num, maxSum = num;

     for (int x = 1; x < numElements; x++)
     {
          cin >> num;
          sum = max(num, sum + num);
          maxSum = max(maxSum, sum);
     }

     return maxSum;
}
working

This website uses cookies

As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://corp.maven.io/privacy-policy

Show Details
Necessary
HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
LoginThis is necessary to sign in to the HubPages Service.
Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
AkismetThis is used to detect comment spam. (Privacy Policy)
HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
Features
Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
MavenThis supports the Maven widget and search functionality. (Privacy Policy)
Marketing
Google AdSenseThis is an ad network. (Privacy Policy)
Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
Index ExchangeThis is an ad network. (Privacy Policy)
SovrnThis is an ad network. (Privacy Policy)
Facebook AdsThis is an ad network. (Privacy Policy)
Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
AppNexusThis is an ad network. (Privacy Policy)
OpenxThis is an ad network. (Privacy Policy)
Rubicon ProjectThis is an ad network. (Privacy Policy)
TripleLiftThis is an ad network. (Privacy Policy)
Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
Statistics
Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
ClickscoThis is a data management platform studying reader behavior (Privacy Policy)