Question Link

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/

Question Description

Given an array of prices[], return maximum profix by choosing a single day to by stock, and different future day to sell stock.
Input: prices = [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. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.

Simulation

Solution 1: Greedy

Greedy by maximize the profit in each single operation, and then maximize the global profit.
Leetcode 121 Best Time to Buy and Sell Stock - 图1

Implementation

Solution

  1. public int maxProfit(int[] prices) {
  2. int profit = 0;
  3. int cost = Integer.MAX_VALUE;
  4. for (int price: prices) {
  5. profit = Math.max(profit, profit - cost);
  6. cost = Math.min(cost, price);
  7. }
  8. return profit;
  9. }