zoukankan      html  css  js  c++  java
  • LeetCode 121. Best Time to Buy and Sell Stock

    分析

    难度 易

    来源

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

    题目

    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.

    解答

     1 package LeetCode;
     2 
     3 public class L121_BestTime2BuyAndSellStock {
     4       public int maxProfit(int[] prices) {
     5         int orginLen=prices.length;
     6         if(orginLen<2)
     7             return 0;
     8         int min=prices[0];
     9         int profit=0;
    10         for(int i=1;i<prices.length;i++){
    11             if(prices[i]<min)
    12                 min=prices[i];
    13             if (prices[i] > prices[i - 1])//减少不必要的Math.max运算
    14                 profit=Math.max(profit,prices[i]-min);
    15         }
    16         return profit;
    17     }
    18     public static void main(String[] args){
    19         L121_BestTime2BuyAndSellStock l121=new L121_BestTime2BuyAndSellStock();
    20         int[] prices={7,1,5,3,6,4};
    21         long timer1=System.currentTimeMillis();
    22         System.out.println(l121.maxProfit(prices));
    23         long timer2=System.currentTimeMillis();
    24     }
    25 }

     

    博客园的编辑器没有CSDN的编辑器高大上啊
  • 相关阅读:
    浏览器跨域访问WebApi
    外部主机无法访问IIS发布的网站
    在VisualStudio中远程调试IIS站点
    关于跨域请求的一些解决方案
    MVC与WebApi中的异常过滤器
    委托与事件
    C#中的属性
    C#中的索引
    Equals与==的区别
    关于跨域响应头Access-Control-Allow-Headers的一些说明
  • 原文地址:https://www.cnblogs.com/flowingfog/p/9907929.html
Copyright © 2011-2022 走看看