Created
March 1, 2015 05:33
-
-
Save kmdarshan/dd79ff6af8969b45b9da to your computer and use it in GitHub Desktop.
Maximum subarray
This file contains 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
// interface | |
@interface MaxSubArray : NSObject | |
@end | |
// extension | |
@interface MaxSubArray() | |
@end | |
@implementation MaxSubArray | |
-(void) maxSubArrayFor:(NSArray*)array { | |
NSInteger bestSumStartIndex = 0; | |
NSInteger bestSumEndIndex = 0; | |
NSInteger maxSum = 0; | |
NSInteger currentIndex = -1; | |
NSInteger currentSum = 0; | |
for (int i=0; i<[array count]; i++) { | |
NSInteger value = currentSum + [[array objectAtIndex:i]integerValue]; | |
if (value > 0) { | |
if (currentSum == 0) { | |
currentIndex = i; | |
} | |
currentSum = value; | |
} else { | |
currentSum = 0; | |
} | |
if (currentSum > maxSum) { | |
maxSum = currentSum; | |
bestSumStartIndex = currentIndex; | |
bestSumEndIndex = i; | |
} | |
} | |
NSLog(@"start %lu end %lu", bestSumStartIndex, bestSumEndIndex); | |
} | |
@end | |
MaxSubArray *subArray = [MaxSubArray new]; | |
[subArray maxSubArrayFor:[NSArray arrayWithObjects:[NSNumber numberWithInteger:-1], [NSNumber numberWithInteger:1], [NSNumber numberWithInteger:3], [NSNumber numberWithInteger:1], [NSNumber numberWithInteger:-5], nil]]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment