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;

    }

}

 
原文地址:https://www.cnblogs.com/codeskiller/p/6358615.html