|
| 1 | +package com.diguage.algorithm.leetcode; |
| 2 | + |
| 3 | +import java.util.Objects; |
| 4 | + |
| 5 | +/** |
| 6 | + * = 121. Best Time to Buy and Sell Stock |
| 7 | + * |
| 8 | + * https://leetcode.com/problems/best-time-to-buy-and-sell-stock/[Best Time to Buy and Sell Stock - LeetCode] |
| 9 | + * |
| 10 | + * Say you have an array for which the ith element is the price of a given stock on day i. |
| 11 | + * |
| 12 | + * 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. |
| 13 | + * |
| 14 | + * Note that you cannot sell a stock before you buy one. |
| 15 | + * |
| 16 | + * .Example 2: |
| 17 | + * [source] |
| 18 | + * ---- |
| 19 | + * Input: [7,1,5,3,6,4] |
| 20 | + * Output: 5 |
| 21 | + * Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. |
| 22 | + * Not 7-1 = 6, as selling price needs to be larger than buying price. |
| 23 | + * ---- |
| 24 | + * |
| 25 | + * .Example 2: |
| 26 | + * [source] |
| 27 | + * ---- |
| 28 | + * Input: [7,6,4,3,1] |
| 29 | + * Output: 0 |
| 30 | + * Explanation: In this case, no transaction is done, i.e. max profit = 0. |
| 31 | + * ---- |
| 32 | + * |
| 33 | + * @author D瓜哥, https://www.diguage.com/ |
| 34 | + * @since 2020-01-01 13:01 |
| 35 | + */ |
| 36 | +public class BestTimeToBuyAndSellStock { |
| 37 | + /** |
| 38 | + * Runtime: 198 ms, faster than 8.08% of Java online submissions for Best Time to Buy and Sell Stock. |
| 39 | + * |
| 40 | + * Memory Usage: 38.5 MB, less than 76.99% of Java online submissions for Best Time to Buy and Sell Stock. |
| 41 | + */ |
| 42 | + public int maxProfit(int[] prices) { |
| 43 | + if (Objects.isNull(prices) || prices.length < 2) { |
| 44 | + return 0; |
| 45 | + } |
| 46 | + int result = 0; |
| 47 | + |
| 48 | + for (int i = 0; i < prices.length - 1; i++) { |
| 49 | + for (int j = i + 1; j < prices.length; j++) { |
| 50 | + int temp = prices[j] - prices[i]; |
| 51 | + if (temp > result) { |
| 52 | + result = temp; |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + return result; |
| 57 | + } |
| 58 | + |
| 59 | + public static void main(String[] args) { |
| 60 | + BestTimeToBuyAndSellStock solution = new BestTimeToBuyAndSellStock(); |
| 61 | + int[] a3 = {2, 7, 1, 4}; |
| 62 | + int r3 = solution.maxProfit(a3); |
| 63 | + System.out.println((r3 == 5) + " : " + r3); |
| 64 | + |
| 65 | + int[] a1 = {7, 1, 5, 3, 6, 4}; |
| 66 | + int r1 = solution.maxProfit(a1); |
| 67 | + System.out.println((r1 == 5) + " : " + r1); |
| 68 | + |
| 69 | + |
| 70 | + int[] a2 = {7, 6, 4, 3, 1}; |
| 71 | + int r2 = solution.maxProfit(a2); |
| 72 | + System.out.println((r2 == 0) + " : " + r2); |
| 73 | + } |
| 74 | +} |
0 commit comments