• [Leetcode] 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 (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

    Solution:

    只需要找到最大增长即可。如图所示,就是找到最大的红线。

    从后往前,用此后最大价格减去当前价格,就是在当前点卖出股票能获得的最高利润。
    扫描的过程中更新最大利润和最高价格就行了。

     1 public class Solution {
     2     public int maxProfit(int[] prices) {
     3         int maxProfit = 0;
     4         if (prices.length == 0)
     5             return maxProfit;
     6         int highest=prices[prices.length-1];
     7         for (int i = prices.length - 1; i >= 0; --i) {
     8             highest=Math.max(highest, prices[i]);
     9             maxProfit=Math.max(maxProfit, highest-prices[i]);
    10         }
    11         return maxProfit;
    12     }
    13 }
  • 相关阅读:
    jsp登录显示
    flask 分页
    module pip has no attribute main
    html active属性
    Centos7配置
    python爬虫笔记----4.Selenium库(自动化库)
    python爬虫笔记
    python报错记录
    mybatis逆向文件
    python简单验证码
  • 原文地址:https://www.cnblogs.com/Phoebe815/p/4027914.html
Copyright © 2020-2023  润新知