Best Time to Buy and Sell Stock

You are given an array prices where prices[i] is the price of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Find the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

Example 1:

Input: prices ={7,1,5,3,6,4}
Output: 5

Approach

Java

import java.util.ArrayList;
import java.util.List;

public class BestTimeBuySellStock {
    public static void main(String[] args) {
        int prices[] = { 715364 };
        System.out.println(maxProfit(prices));
    }

    static int maxProfit(int[] prices) {
        List<int[]> v = new ArrayList<int[]>();
        int n = prices.length;
        if (n == 0)
            return 0;
        int max1 = prices[n - 1];
        for (int i = n - 1; i >= 0; i--) {
            max1 = Math.max(max1, prices[i]);
            v.add(new int[] { prices[i], max1 });
        }
        int res = 0;
        for (int i = 0; i < n; i++) {
            if (v.get(i)[1] - v.get(i)[0] > res)
                res = v.get(i)[1] - v.get(i)[0];
        }
        return res;
    }

}

C++

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


int maxProfit(vector<int>& prices
{
        vector<pair<int,int>> v;
        int n=prices.size();
        if(n==0)
              return 0;
        int max1=prices[n-1];
        for(int i=n-1;i>=0;i--)
        {
            max1=max(max1,prices[i]);
            v.push_back({prices[i],max1});
        }
        int res=0;
        for(int i=0;i<n;i++)
        {
            if(v[i].second-v[i].first>res)
                  res=v[i].second-v[i].first;
        }
        return res;
}

int main()  
{
    vector<intprices ={7,1,5,3,6,4};
    cout<<maxProfit(prices);
    return 0;
}




No comments:

Post a Comment