Skip to content

Instantly share code, notes, and snippets.

@alesolano
Created August 21, 2019 09:09
Show Gist options
  • Save alesolano/b64cce51a5802dab0126c34f9d5b7dd6 to your computer and use it in GitHub Desktop.
Save alesolano/b64cce51a5802dab0126c34f9d5b7dd6 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <vector>
#include "solution.h"
int main()
{
std::vector<int> prices = {5, 3, 7, 1, 5, 3, 6, 4};
Solution* sol = new Solution();
int best_profit = sol->maxProfit(prices);
std::cout << "The best profit is " << best_profit << std::endl;
delete(sol);
return 0;
}

Best time to buy and sell stock

From: https://leetcode.com/explore/featured/card/top-interview-questions-easy/97/dynamic-programming/572/

Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. Note that you cannot sell a stock before you buy one.

Example 1:

  • Input: [7,1,5,3,6,4]
  • Output: 5
  • Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Not 7-1 = 6, as selling price needs to be larger than buying price.

Example 2:

  • Input: [7,6,4,3,1]
  • Output: 0
  • Explanation: In this case, no transaction is done, i.e. max profit = 0.
#include <vector>
#include <limits>
#include "solution.h"
int Solution::maxProfit(std::vector<int>& prices)
{
int min_buy_price = std::numeric_limits<int>::max();
int best_profit = 0;
for (int buy_day = 0; buy_day < prices.size(); ++buy_day)
{
if (prices[buy_day] < min_buy_price)
{
min_buy_price = prices[buy_day];
}
else if ((prices[buy_day] - min_buy_price) > best_profit)
{
best_profit = prices[buy_day] - min_buy_price;
}
}
return best_profit;
}
#pragma once
class Solution
{
public:
int maxProfit(std::vector<int>& prices);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment