zoukankan      html  css  js  c++  java
  • <LeetCode>121. 买卖股票的最佳时机

    题目:

    假设你有一个数组,其中第 i 个元素是一支给定股票第 i 天的价格。

    如果您只能完成最多一笔交易(即买入和卖出一股股票),则设计一个算法来找到最大的利润。

    示例1:

    1 输入: [7, 1, 5, 3, 6, 4]
    2 输出: 5
    3 
    4 最大利润 = 6-1 = 5(不是 7-1 = 6, 因为卖出价格需要大于买入价格)

    示例2:

    1 输入: [7, 6, 4, 3, 1]
    2 输出: 0
    3 
    4 在这种情况下, 没有交易完成, 即最大利润为 0。

    思路:

    result 永远保存最大的差值,buy 永远保存最小的价格。

    code:

     1 public class Main{
     2     public static void main(String[] args) {
     3         int[] prices ={7, 1, 5, 3, 6, 4};
     4         System.out.println(maxProfit(prices));
     5 
     6     }
     7     public static int maxProfit(int[] prices){
     8         int buy = Integer.MAX_VALUE;
     9         int result = 0;
    10         for (int i = 1; i<prices.length;i++){
    11             buy = Math.min(prices[i], buy);
    12             result = Math.max(result, prices[i] - buy);
    13         }
    14         return result;
    15     }
    16 
    17 }
  • 相关阅读:
    Qt笔记之 信号和槽
    Qt笔记之 坐标系
    Qt笔记之 QPushButton
    点双连通
    bzoj 2179 FFT快速傅立叶
    bzoj 4128 矩阵求逆
    bzoj 3924 点分
    bzoj 1076 状态压缩最优期望
    bzoj 3143 随机游走
    bzoj 4084 双旋转字符串
  • 原文地址:https://www.cnblogs.com/yumingxing/p/9580348.html
Copyright © 2011-2022 走看看