-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path63_MaximalProfit.cpp
More file actions
118 lines (97 loc) · 2.61 KB
/
63_MaximalProfit.cpp
File metadata and controls
118 lines (97 loc) · 2.61 KB
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
/*******************************************************************
Copyright(c) 2016, Harry He
All rights reserved.
Distributed under the BSD license.
(See accompanying file LICENSE.txt at
https://github.com/zhedahht/CodingInterviewChinese2/blob/master/LICENSE.txt)
*******************************************************************/
//==================================================================
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 作者:何海涛
//==================================================================
// 面试题63:股票的最大利润
// 题目:假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖交易该股
// 票可能获得的利润是多少?例如一只股票在某些时间节点的价格为{9, 11, 8, 5,
// 7, 12, 16, 14}。如果我们能在价格为5的时候买入并在价格为16时卖出,则能
// 收获最大的利润11。
#include <cstdio>
int MaxDiff(const int* numbers, unsigned length)
{
if(numbers == nullptr && length < 2)
return 0;
int min = numbers[0];
int maxDiff = numbers[1] - min;
for(int i = 2; i < length; ++i)
{
if(numbers[i - 1] < min)
min = numbers[i - 1];
int currentDiff = numbers[i] - min;
if(currentDiff > maxDiff)
maxDiff = currentDiff;
}
return maxDiff;
}
// ==================== Test Code ====================
void Test(const char* testName, const int* numbers, unsigned int length, int expected)
{
if(testName != nullptr)
printf("%s begins: ", testName);
if(MaxDiff(numbers, length) == expected)
printf("Passed.\n");
else
printf("FAILED.\n");
}
void Test1()
{
int numbers[] = { 4, 1, 3, 2, 5 };
Test("Test1", numbers, sizeof(numbers) / sizeof(int), 4);
}
// 价格递增
void Test2()
{
int numbers[] = { 1, 2, 4, 7, 11, 16 };
Test("Test2", numbers, sizeof(numbers) / sizeof(int), 15);
}
// 价格递减
void Test3()
{
int numbers[] = { 16, 11, 7, 4, 2, 1 };
Test("Test3", numbers, sizeof(numbers) / sizeof(int), -1);
}
// 价格全部相同
void Test4()
{
int numbers[] = { 16, 16, 16, 16, 16 };
Test("Test4", numbers, sizeof(numbers) / sizeof(int), 0);
}
void Test5()
{
int numbers[] = { 9, 11, 5, 7, 16, 1, 4, 2 };
Test("Test5", numbers, sizeof(numbers) / sizeof(int), 11);
}
void Test6()
{
int numbers[] = { 2, 4 };
Test("Test6", numbers, sizeof(numbers) / sizeof(int), 2);
}
void Test7()
{
int numbers[] = { 4, 2 };
Test("Test7", numbers, sizeof(numbers) / sizeof(int), -2);
}
void Test8()
{
Test("Test8", nullptr, 0, 0);
}
int main(int argc, char* argv[])
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
Test7();
Test8();
return 0;
}