Skip to content

Instantly share code, notes, and snippets.

@OscarSwanros
Last active December 30, 2015 20:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OscarSwanros/7884796 to your computer and use it in GitHub Desktop.
Save OscarSwanros/7884796 to your computer and use it in GitHub Desktop.
Get the maximum sum (subarray) from an array
#import "MSViewController.h"
@interface MSViewController ()
@end
@implementation MSViewController
- (void)viewDidLoad
{
[super viewDidLoad];
int vals[] = { -1,1, 5,-5, 10, 4, 3, 9};
int n = sizeof(vals) / sizeof(vals[0]);
NSLog(@"%d", [self maximumWithElementsOfArray:vals numberOfItems:n]);
}
- (int)maximumWithElementsOfArray:(int[])array numberOfItems:(int)number{
int max_ending_here;
int max_so_far;
max_ending_here = max_so_far = array[0];
for (int i = 0; i < number; i++) {
max_ending_here = MAX(array[i], max_ending_here + array[i]);
max_so_far = MAX(max_so_far, max_ending_here);
}
return max_so_far;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment