-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbuy_and_sell.cpp
More file actions
38 lines (27 loc) · 973 Bytes
/
buy_and_sell.cpp
File metadata and controls
38 lines (27 loc) · 973 Bytes
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
//
// Created by Mayank Parasar on 2019-12-19.
//
/*
* You are given an array. Each element represents the price of a stock on that particular day.
* Calculate and return the maximum profit you can make from buying and selling that stock only once.
For example: [9, 11, 8, 5, 7, 10]
Here, the optimal trade is to buy when the price is 5, and sell when it is 10,
so the return value should be 5 (profit = 10 - 5 = 5).
*/
#include <iostream>
#include <vector>
using namespace std;
int maximum_possible_profit(vector<int>& stocks) {
vector<int> profit;
for(int ii = 0; ii < stocks.size(); ++ii) { // bought
for(int jj = ii; jj < stocks.size(); ++jj) { // sold
profit.push_back(stocks[jj] - stocks[ii]); // profit : sold - bought
}
}
return(*max_element(profit.begin(), profit.end()));
}
int main() {
vector<int> stocks = {9, 11, 8, 5, 7, 10};
cout << maximum_possible_profit(stocks);
return 0;
}