zoukankan      html  css  js  c++  java
  • [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 }
  • 相关阅读:
    spring 注解笔记
    spring boot 拦截器
    spring boot 启动流程及其原理
    Spring之BeanFactory和FactoryBean接口的区别
    微信支付
    三级联动
    搜索分页
    多选标签
    分类界面 大分类小分类
    触底下拉
  • 原文地址:https://www.cnblogs.com/Phoebe815/p/4027914.html
Copyright © 2011-2022 走看看