Created
November 7, 2013 15:22
-
-
Save CDRussell/7356385 to your computer and use it in GitHub Desktop.
Solution to the Coin Change Problem in Objective-C
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
// just the method body; complete the rest of the class declaration yourself. | |
+ (BOOL)isValidAmount:(int)target forDenominations:(NSArray *)denominations | |
{ | |
if(denominations.count == 0) | |
return NO; | |
if(target < 0) | |
return NO; | |
if(target == 0) | |
return YES; | |
NSMutableArray *results = [NSMutableArray arrayWithCapacity:target + 1]; | |
for(int i = 0; i < target+1; i++) | |
{ | |
[results insertObject:[NSNumbernumberWithInt:0] atIndex:i]; | |
} | |
[results replaceObjectAtIndex:0withObject:[NSNumbernumberWithInt:1]]; | |
for(int i = 0; i < denominations.count; i++) | |
{ | |
for(int j = [denominations[i] intValue]; j <= target; j++) | |
{ | |
int difference = j - [denominations[i] intValue]; | |
[results replaceObjectAtIndex:j withObject:[NSNumber numberWithInt:[results[j] intValue] + [results[difference] intValue]]]; | |
if(j == target && [results[j] intValue] > 0) | |
return YES; | |
} | |
} | |
returnNO; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment