Stock Buy Sell for Maximum Profit
The cost of a stock on each day is given in an array. Find the maximum profit that you can make by buying and selling on those days. If the given array of prices is sorted in decreasing order, then profit cannot be earned at all.
Examples:
Input: arr[] = {4, 2, 2, 2, 4}
Output: 2
Explanation: Buy the stock on day 1 and sell it on day 4 => 4 – 2 = 2
Maximum Profit = 2
Input: arr[] = {100, 180, 260, 310, 40, 535, 695}
Output: 865
Explanation: Buy the stock on day 0 and sell it on day 3 => 310 – 100 = 210
Buy the stock on day 4 and sell it on day 6 => 695 – 40 = 655
Maximum Profit = 210 + 655 = 865
Solution:
#include <iostream>
using namespace std;
int maxProfit(int* prices, int size)
{
int maxProfit = 0;
// The loop starts from 1
// as its comparing with the previous
for (int i = 1; i < size; i++)
{
if (prices[i] > prices[i - 1])
maxProfit += prices[i] - prices[i - 1];
}
return maxProfit;
}
int main()
{
int prices[] = { 100, 180, 260, 310, 40, 535, 695 };
int N = sizeof(prices) / sizeof(prices[0]);
cout << maxProfit(prices, N) << endl;
return 0;
}