The best time to buy or sell stocks

Given an array of prices, the ith element of prices[I] represents the price of a given stock on day I.

You can only buy the stock on a certain day and sell it on a different date in the future. Design an algorithm to calculate the maximum profit you can make.

Return the maximum profit you can make from the transaction. If you can’t make any profit, return 0.

See the LeetCode website for an example.

Source: LeetCode Link:… Copyright belongs to collar network. Commercial reprint please contact the official authorization, non-commercial reprint please indicate the source.

Solution one: dynamic programming

If prices are empty or if prices have only one value, return 0;

Otherwise, we declare a variable result = 0, buyPrice = the first value of prices, and traverse from the second value of prices:

  • If the current value is equal to buyPrice, then the processing of the next value is skipped;
  • If the current value is less than buyPrice, update buyPrice to the current value;
  • If the current value is greater than buyPrice, determine whether the difference between the current value and buyPrice is greater than result. If it is greater, update the value of result.

When the traversal is complete, result is returned.

public class LeetCode_121 { public static int maxProfit(int[] prices) { if (prices == null || prices.length < 2) { return 0; } int result = 0; int buyPrice = prices[0]; for (int i = 1; i < prices.length; i++) { if (prices[i] == buyPrice) { continue; } else if (prices[i] < buyPrice) { buyPrice = prices[i]; } else { if (prices[i] - buyPrice > result) { result = prices[i] - buyPrice; } } } return result; } public static void main(String[] args) { int[] prices = new int[]{7, 1, 5, 3, 6, 4}; System.out.println(maxProfit(prices)); }}

【 Daily Message 】
March goes quietly, April comes lightly. The most beautiful April day, do not negative the beauty of spring. The road ahead is smooth, everything may be expected.