Skip to content

Commit

Permalink
Best time to buy and sell stock
Browse files Browse the repository at this point in the history
Signed-off-by: begeekmyfriend <[email protected]>
  • Loading branch information
begeekmyfriend committed Nov 9, 2017
1 parent f1f85b6 commit e6b82a9
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
2 changes: 2 additions & 0 deletions 123_best_time_to_buy_and_sell_stock_iii/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
all:
gcc -O2 -o test stock.c
48 changes: 48 additions & 0 deletions 123_best_time_to_buy_and_sell_stock_iii/stock.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
#include <stdio.h>
#include <stdlib.h>

static int maxProfit(int* prices, int pricesSize)
{
if (pricesSize == 0) {
return 0;
}

int i, tmp, diff = 0, min = prices[0];
int *left_profit = malloc(pricesSize * sizeof(int));
for (i = 1; i < pricesSize; i++) {
if (prices[i] < min) {
min = prices[i];
} else {
tmp = prices[i] - min;
diff = tmp > diff ? tmp : diff;
}
left_profit[i] = diff;
}

int right_profit = 0;
int max = prices[pricesSize - 1];
int total = left_profit[pricesSize - 1];
for (i = pricesSize - 2; i >= 0; i--) {
if (prices[i] > max) {
max = prices[i];
} else {
tmp = max - prices[i];
right_profit = tmp > right_profit ? tmp : right_profit;
}
tmp = left_profit[i] + right_profit;
total = tmp > total ? tmp : total;
}

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;
}

0 comments on commit e6b82a9

Please sign in to comment.