Skip to content

Commit e6b82a9

Browse files
Best time to buy and sell stock
Signed-off-by: begeekmyfriend <begeekmyfriend@gmail.com>
1 parent f1f85b6 commit e6b82a9

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
all:
2+
gcc -O2 -o test stock.c
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
static int maxProfit(int* prices, int pricesSize)
5+
{
6+
if (pricesSize == 0) {
7+
return 0;
8+
}
9+
10+
int i, tmp, diff = 0, min = prices[0];
11+
int *left_profit = malloc(pricesSize * sizeof(int));
12+
for (i = 1; i < pricesSize; i++) {
13+
if (prices[i] < min) {
14+
min = prices[i];
15+
} else {
16+
tmp = prices[i] - min;
17+
diff = tmp > diff ? tmp : diff;
18+
}
19+
left_profit[i] = diff;
20+
}
21+
22+
int right_profit = 0;
23+
int max = prices[pricesSize - 1];
24+
int total = left_profit[pricesSize - 1];
25+
for (i = pricesSize - 2; i >= 0; i--) {
26+
if (prices[i] > max) {
27+
max = prices[i];
28+
} else {
29+
tmp = max - prices[i];
30+
right_profit = tmp > right_profit ? tmp : right_profit;
31+
}
32+
tmp = left_profit[i] + right_profit;
33+
total = tmp > total ? tmp : total;
34+
}
35+
36+
return total;
37+
}
38+
39+
int main(int argc, char **argv)
40+
{
41+
int i, count = argc - 1;
42+
int *nums = malloc(count * sizeof(int));
43+
for (i = 0; i < count; i++) {
44+
nums[i] = atoi(argv[i + 1]);
45+
}
46+
printf("%d\n", maxProfit(nums, count));
47+
return 0;
48+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy