Question: This problem is the same as #1, except you may complete as many buy/sell orders as you have to in a given time slice AND
This problem is the same as #1, except you may complete as many buy/sell orders as you have to in a given time slice AND you must sell one before you can buy another (except for the very first buy order).
Write the following function taking in an integer vector (vector
int getMaxProfit(vector&prices)
Examples:
input: {1,2,4}
output: 3
note on output: buy $1, sell $2, buy $2, sell $4 => $1+$2 = $3 profit
input: {4,2,1}
output: 0
note on output: you will not be able to buy low, sell high in this pricing order => no buy, no sell => $0 profit
input: {1}
output: 0
note on output: this may be the time slice at the end of the trading day; if you buy in at $1 you lose money since you won't be able to sell it before market closes
input: {1,2,5,1,6}
output: 9
note on output: buy $1, sell $2, buy $2, sell $5, buy $1, sell $6 => $1 + $3 + $5 = $9 profit
input: {3,1,5,2,4}
output: 6
note on output: buy $1, sell $5, buy $2, sell $4 => $4 + $2 = $6 profit
Constraints / Assumptions:
For this problem, you may have multiple buy-sell orders BUT you must sell one before you can buy again (except for the very first purchase)
The multiple order requirement comes from the fact that you may just have enough money to buy one order to start with, and you are making small incremental profits by selling high like a day trader would for many times in a day
Prices are in USD ($) and are > 0
Input is passed in by reference
Max Profit (output) is defined as the max price difference between your buy and sell prices ($profit = ($sell - $buy))
Input cannot be empty and it has at least one price data
Output is your max profit based on the input (vector
You should submit a fully working console program however your main() function isn't graded; only the above referenced function is
It is your responsibility to compile your code in C++11/C++14 (no pre-C++11!). Failure to do that means your code isn't compilable and you will receive 0 point!
Failure to follow the same exact function signature receives -1 styling point deduction
Food for thought: can you get your solution to within O(n)?
Logic: 9 points (-1 point for each test case failure); 1 point for function signature
Styling/Documentation: 1 point
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
