FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
algorithm-examples/cpp-algorithm/src/array/stock_trading.cpp at main · codejsha/algorithm-examples · GitHub
codejsha
/
algorithm-examples
Public
Notifications
You must be signed in to change notification settings
Fork
0
Star
2
Code
Issues
0
Pull requests
0
Discussions
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Discussions
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
algorithm-examples
/
cpp-algorithm
/
src
/
array
/
stock_trading.cpp
Copy path
More file actions
More file actions
Latest commit
History
History
History
59 lines (48 loc) · 1.8 KB
Breadcrumbs
algorithm-examples
/
cpp-algorithm
/
src
/
array
/
stock_trading.cpp
Copy path
File metadata and controls
59 lines (48 loc) · 1.8 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
#
include
"
stock_trading.h
"
#
include
<
limits
>
auto
StockTrading::BuyAndSellStockOnceBruteForce
(
const
std::vector<
int
>& prices) -> double
{
double
max_profit =
0.0
;
for
(
int
i =
0
; i <
static_cast
<
int
>(prices.
size
()); ++i)
{
for
(
int
j = i +
1
; j <
static_cast
<
int
>(prices.
size
()); ++j)
{
if
(
const
int
profit = prices[j] - prices[i]; profit > max_profit)
{
max_profit = profit;
}
}
}
return
max_profit;
}
auto
StockTrading::BuyAndSellStockOnce
(
const
std::vector<
int
>& prices) -> double
{
double
min_price_so_far = std::numeric_limits<
double
>::
infinity
();
double
max_profit =
0.0
;
for
(
double
price : prices)
{
double
max_profit_sell_today = price - min_price_so_far;
max_profit =
std::max
(max_profit, max_profit_sell_today);
min_price_so_far =
std::min
(min_price_so_far, price);
}
return
max_profit;
}
auto
StockTrading::BuyAndSellStockTwice
(
const
std::vector<
double
>& prices) -> double
{
double
max_total_profit =
0
;
std::vector<
double
>
first_buy_sell_profits
(prices.
size
(),
0
);
double
min_price_so_far = std::numeric_limits<
double
>::
infinity
();
for
(
int
i =
0
; i <
static_cast
<
int
>(prices.
size
()); ++i)
{
min_price_so_far =
std::min
(min_price_so_far, prices[i]);
max_total_profit =
std::max
(max_total_profit, prices[i] - min_price_so_far);
first_buy_sell_profits[i] = max_total_profit;
}
double
max_price_so_far = std::numeric_limits<
double
>::
min
();
for
(
int
i =
static_cast
<
int
>(prices.
size
()) -
1
; i >
0
; --i)
{
max_price_so_far =
std::max
(max_price_so_far, prices[i]);
max_total_profit =
std::max
(max_total_profit, max_price_so_far - prices[i] + first_buy_sell_profits[i]);
}
return
max_total_profit;
}
Back
|
FazBrowse Home
|
New Git URL