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.

    Example 1:

    Input: [7, 1, 5, 3, 6, 4]
    Output: 5
    
    max. difference = 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
    
    In this case, no transaction is done, i.e. max profit = 0.
    

     此题属于动态规划问题,动态规划的特点原问题可以被分解为若干规模较小的子问题,注意状态方程,当遍历到数组的某一值时,如果该值比之前最小元素还小,则将其保存为最小元素,否则,差值就是到该数组值的时候,最大的利润。代码如下:

    public class Solution {

        public int maxProfit(int[] prices) {

            int max = 0;

            if(prices.length==0) return max;

            int start = prices[0];

            for(int i=1;i<prices.length;i++){

                if(prices[i]<start){

                    start = prices[i];

                }else{

                    max = Math.max(max,prices[i]-start);

                }

            }

            return max;

        }

    }

     
  • 相关阅读:
    spring+mybatis+druid+xml
    springboot run(),bean注册
    linux命令之cat
    linux命令之more
    linux中配置maven环境
    linux中配置Java环境
    linux命令之nohup
    在Eclipse中创建Maven多模块工程的例子
    MINA之心跳协议运用
    Java动态代理
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6358615.html
Copyright © 2011-2022 走看看