Last active
December 30, 2015 20:59
-
-
Save OscarSwanros/7884796 to your computer and use it in GitHub Desktop.
Get the maximum sum (subarray) from an array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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