zoukankan      html  css  js  c++  java
  • 121-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.

    思路:

    1.目标是求数组中的某两个值的差(最大差值),前提是大的数在小的数后面

    2.循环遍历数组,设置一个当前最小值min(初始为Integer.MAX_VALUE)和一个最大差值max(初始化为0)

       每次更新min,并更新max(当前元素值-min)

    public class Solution {
        public int maxProfit(int[] prices) {
             int len=prices.length;     //数组长度
             int max=0;                    //最大差值
             int min=Integer.MAX_VALUE;              //当前最小值
             for(int i=0;i<len;i++) {
                 if(prices[i]<min)
                      min=prices[i];
                 if(prices[i]-min>max)
                      max=prices[i]-min;
             }
             return max;
        }
    }
    

      

  • 相关阅读:
    tomcat并发个题-未解决
    tengine安装
    nginx获得自定义参数
    nginx限流
    树形背包——hdu1561
    树形dp专题
    单调队列——P1725 琪露诺
    单调队列,dp——POJ
    记忆化搜索——HDU
    区间dp——POJ
  • 原文地址:https://www.cnblogs.com/hwu2014/p/4422009.html
Copyright © 2011-2022 走看看