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 Sep 19, 2017
1 parent 2d37950 commit 995b5e2
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 4 deletions.
15 changes: 11 additions & 4 deletions 121_best_time_to_buy_and_sell_stock/stock.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
2 changes: 2 additions & 0 deletions 122_best_time_to_buy_and_sell_stock_ii/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
all:
gcc -O2 -o test stock.c
24 changes: 24 additions & 0 deletions 122_best_time_to_buy_and_sell_stock_ii/stock.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>

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

0 comments on commit 995b5e2

Please sign in to comment.