Best Time to Buy and Sell Stock - Easy

less than 1 minute read

Published:

Question

  • https://leetcode.com/problems/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.

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

Approach

  • Iteration
  • https://medium.com/algorithms-and-leetcode/best-time-to-buy-sell-stocks-on-leetcode-the-ultimate-guide-ce420259b323

Solution

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int min_num = prices[0];
        int max_num = INT_MIN;
        int ans = 0;
        int n = prices.size();
        for(int i=1; i<n; i++) {
            if (prices[i] > min_num) {
                if (ans < (prices[i] - min_num)) {
                    ans = prices[i] - min_num;
                }
            }
            if (min_num > prices[i]) {
                min_num = prices[i];
            }
        }
        return ans;
    }
};