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;

        }

    }

     
  • 相关阅读:
    链表操作
    51nod1085-----01背包
    51nod1046快速幂取余
    51nod贪心算法入门-----任务分配问题
    51nod动态规划-----矩阵取数
    51nod贪心算法入门-----独木舟问题
    POJ2255二叉树
    POJ1182并查集
    POJ1384完全背包问题
    20162313_苑洪铭_ 第7周学习总结
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6358615.html
Copyright © 2011-2022 走看看