Skip to content

Instantly share code, notes, and snippets.

@mrnkr
Last active December 16, 2019 14:20
Show Gist options
  • Save mrnkr/c8f59ee5481be5ef6f4d4d9c3458d03a to your computer and use it in GitHub Desktop.
Save mrnkr/c8f59ee5481be5ef6f4d4d9c3458d03a to your computer and use it in GitHub Desktop.
Quick coding challenge - given an array of numbers let i the current element, calculate x as the difference between i and some element after it so as to maximize x
#include<stdio.h>
int max(int a, int b) {
return a > b ? a : b;
}
int max_profit(int* values, size_t len) {
if (len == 1) return 0;
int ret = 0;
int cur = *values;
int* upcoming = values + 1;
for (int i = 0; i < len - 1; ++i) {
int profit = *(upcoming + i) - cur;
if (ret < profit) {
ret = profit;
}
}
return max(ret, max_profit(upcoming, len - 1));
}
int main() {
int prices[6] = {10, 7, 5, 8, 11, 9};
size_t len = 6;
int profit = max_profit(prices, len);
printf("You will earn $%d\n", profit);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment