diff --git a/121_best_time_to_buy_and_sell_stock/stock.c b/121_best_time_to_buy_and_sell_stock/stock.c index a960599..b711785 100644 --- a/121_best_time_to_buy_and_sell_stock/stock.c +++ b/121_best_time_to_buy_and_sell_stock/stock.c @@ -3,12 +3,19 @@ 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; + if (pricesSize == 0) { + return 0; + } + + int i, diff = 0, min = prices[0]; + for (i = 1; i < pricesSize; i++) { + if (prices[i] < min) { + min = prices[i]; + } else { + diff = prices[i] - min > diff ? prices[i] - min : diff; } } + return diff; } diff --git a/122_best_time_to_buy_and_sell_stock_ii/Makefile b/122_best_time_to_buy_and_sell_stock_ii/Makefile new file mode 100644 index 0000000..c638fbb --- /dev/null +++ b/122_best_time_to_buy_and_sell_stock_ii/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test stock.c diff --git a/122_best_time_to_buy_and_sell_stock_ii/stock.c b/122_best_time_to_buy_and_sell_stock_ii/stock.c new file mode 100644 index 0000000..8c53220 --- /dev/null +++ b/122_best_time_to_buy_and_sell_stock_ii/stock.c @@ -0,0 +1,24 @@ +#include +#include +#include +#include + +static int maxProfit(int* prices, int pricesSize) +{ + int i, j, total = 0; + for (i = 1; i < pricesSize; i++) { + total += prices[i] > prices[i - 1] ? prices[i] - prices[i - 1] : 0; + } + return total; +} + +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; +}