File tree Expand file tree Collapse file tree 2 files changed +50
-0
lines changed
123_best_time_to_buy_and_sell_stock_iii Expand file tree Collapse file tree 2 files changed +50
-0
lines changed Original file line number Diff line number Diff line change 1+ all :
2+ gcc -O2 -o test stock.c
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments