-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoffer-63-MaximalProfit.c
98 lines (86 loc) · 1.84 KB
/
offer-63-MaximalProfit.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <stdio.h>
/**
* brute force, time complexity: O(n^2), space complexity: O(1)
*/
int maxProfit(int *prices, int pricesSize)
{
int maxVal = 0;
if (prices == NULL || pricesSize <= 1)
{
return maxVal;
}
for (int i = 0; i < pricesSize; i++)
{
for (int j = i + 1; j < pricesSize; j++)
{
int minus = prices[j] - prices[i];
if (minus > maxVal)
{
maxVal = minus;
}
}
}
return maxVal;
}
/**
* two pointers, time complexity: O(n), space complexity: O(1)
*/
int maxProfit2(int *prices, int pricesSize)
{
int maxVal = 0;
if (prices == NULL || pricesSize <= 1)
{
return maxVal;
}
int minVal = prices[0];
for (int i = 1; i < pricesSize; i++)
{
int minus = prices[i] - minVal;
if (minus > maxVal)
{
maxVal = minus;
}
if (prices[i] < minVal)
{
minVal = prices[i];
}
}
return maxVal;
}
/**
* two pointers, time complexity: O(n), space complexity: O(1) ===> enhance maxProfit2
*/
int maxProfit3(int *prices, int pricesSize)
{
int maxVal = 0;
if (prices == NULL || pricesSize <= 1)
{
return maxVal;
}
int minVal = prices[0];
for (int i = 1; i < pricesSize; i++)
{
if (prices[i] < minVal)
{
minVal = prices[i];
continue;
}
int minus = prices[i] - minVal;
if (minus > maxVal)
{
maxVal = minus;
}
}
return maxVal;
}
int main()
{
int a[] = {7, 1, 5, 3, 6, 4};
printf("%d\n", maxProfit(a, (int)(sizeof(a) / sizeof(a[0]))));
printf("%d\n", maxProfit2(a, (int)(sizeof(a) / sizeof(a[0]))));
printf("%d\n", maxProfit3(a, (int)(sizeof(a) / sizeof(a[0]))));
int b[] = {7, 6, 4, 3, 1};
printf("%d\n", maxProfit(b, (int)(sizeof(b) / sizeof(b[0]))));
printf("%d\n", maxProfit2(b, (int)(sizeof(b) / sizeof(b[0]))));
printf("%d\n", maxProfit3(a, (int)(sizeof(a) / sizeof(a[0]))));
}