Skip to content

Instantly share code, notes, and snippets.

@CDRussell
Created November 7, 2013 15:22
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 CDRussell/7356385 to your computer and use it in GitHub Desktop.
Save CDRussell/7356385 to your computer and use it in GitHub Desktop.
Solution to the Coin Change Problem in Objective-C
// 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