Max profit

Given an array where each index represents a day and elements of the array represent the price of stocks on the previous day. Prince decided to buy a stock and then sell that stock to earn maximum profit. 
Find out the maximum profit which he can earn.

Example:

Input:  n = 4, a  = [2, 100, 150, 120]
Output: 148

Approach

C++

#include <bits/stdc++.h>
using namespace std;

int maxProfit(int nint a[])
{
    int buy = a[0];
    int max1 = INT_MIN;
    for (int i = 1i < n - 1i++)
    {
        if (a[i] < buy)
        {
            buy = a[i];
        }
        else
        {
            max1 = max(a[i] - buymax1);
        }
    }
    return max1;
}
int main()
{
    int n = 4;

    int a[n] = {2100150120};

    cout << maxProfit(na<< "\n";

    return 0;
}


No comments:

Post a Comment