Skip to content

Instantly share code, notes, and snippets.

@aragaer
Created April 4, 2012 13:36
Show Gist options
  • Select an option

  • Save aragaer/2301082 to your computer and use it in GitHub Desktop.

Select an option

Save aragaer/2301082 to your computer and use it in GitHub Desktop.
#include <stdio.h>
int data[] = { 3, 4, 6, 5, 11, 2, 19, 1};
int main() {
int min, when_min, buy, sell;
int i;
int profit;
profit = when_min = buy = sell = 0;
min = data[0];
for (i = 0; i < sizeof(data) / sizeof(*data); i++) {
if (min > data[i]) {
min = data[i];
when_min = i;
}
if (data[i] - min > profit) {
profit = data[i] - min;
buy = when_min;
sell = i;
}
}
printf("buy on %d for %d, sell on %d for %d, profit %d\n", buy, data[buy], sell, data[sell], profit);
}
#include <stdio.h>
int data[] = { 3, 4, 6, 5, 11, 2, 9, 1};
int main() {
int *max, *buy, *sell, *ptr;
int profit;
profit = 0;
ptr = max = buy = sell = data + sizeof(data) / sizeof(*data) - 1;
do {
if (*max < *ptr)
max = ptr;
if (*max - *ptr > profit) {
profit = *max - *ptr;
buy = ptr;
sell = max;
}
} while (ptr-- > data);
printf("buy on %d for %d, sell on %d for %d, profit %d\n", buy - data, *buy, sell - data, *sell, profit);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment