From 2d37950adecf72c010686b0656bbb813729de87c Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Mon, 18 Sep 2017 10:11:27 +0800 Subject: [PATCH] Best time to buy and sell stock Signed-off-by: begeekmyfriend --- 121_best_time_to_buy_and_sell_stock/Makefile | 2 ++ 121_best_time_to_buy_and_sell_stock/stock.c | 24 ++++++++++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 121_best_time_to_buy_and_sell_stock/Makefile create mode 100644 121_best_time_to_buy_and_sell_stock/stock.c diff --git a/121_best_time_to_buy_and_sell_stock/Makefile b/121_best_time_to_buy_and_sell_stock/Makefile new file mode 100644 index 0000000..c638fbb --- /dev/null +++ b/121_best_time_to_buy_and_sell_stock/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test stock.c diff --git a/121_best_time_to_buy_and_sell_stock/stock.c b/121_best_time_to_buy_and_sell_stock/stock.c new file mode 100644 index 0000000..a960599 --- /dev/null +++ b/121_best_time_to_buy_and_sell_stock/stock.c @@ -0,0 +1,24 @@ +#include +#include + +static int maxProfit(int* prices, int pricesSize) +{ + int i, j, diff = 0; + for (i = 0; i < pricesSize; i++) { + for (j = i + 1; j < pricesSize; j++) { + diff = prices[j] - prices[i] > diff ? prices[j] - prices[i] : diff; + } + } + return diff; +} + +int main(int argc, char **argv) +{ + int i, count = argc - 1; + int *nums = malloc(count * sizeof(int)); + for (i = 0; i < count; i++) { + nums[i] = atoi(argv[i + 1]); + } + printf("%d\n", maxProfit(nums, count)); + return 0; +}