oj121. Best Time to Buy and Sell Stock

来源:互联网 发布:阿里云cdn缓存配置 编辑:程序博客网 时间:2024/06/06 08:23

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: 5max. 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: 0In this case, no transaction is done, i.e. max profit = 0.
翻译假设你有一个数组,其中第i 个元素是第i天给定股票的价格。如果只允许最多完成一个交易(即购买一个交易并且卖出一个股票),则设计一个算法来找到最大利润。示例1:输入:[7,1,5,3,6,4] 输出:5 最大。差= 6-1 = 5(不是7-1 = 6,因为售价需要大于购买价格)示例2:输入:[ 7,6,4,3,1 ] 输出:0 在这种情况下,没有交易完成,即最大利润= 0。
原始思路:两个循环,buy取出前面买入的价格,原数组buy后面的元素新建一个数组,进行排序,找出最大的减去buy。时间复杂度不符合要求。
public class Solution {    public int maxProfit(int[] prices) {        int result = 0;        for(int i = 0;i<prices.length-1;i++){            int buy = prices[i];            int[] new_prices = new int[prices.length-i-1];            int k =0;            for(int j = i+1;j<prices.length;j++){                new_prices[k]=prices[j];                k++;            }            Arrays.sort(new_prices);            int sell = new_prices[new_prices.length-1];            if(sell - buy >result) result = sell -buy;        }        return result;    }}
大神思路:一个循环搞定,把数组分成几个连续递增的小段。
如果后面的元素比当前对比元素大,则相减得到当前的差值,当前最小元素不变。如果后面的元素比当前对比元素小,则替换当前最小元素。
public int maxProfit(int[] prices) {        if(prices.length == 0){            return 0;        }        int curmin = prices[0];        int max = 0;        for(int i=0;i<prices.length;i++){            if(prices[i]>curmin){                max = Math.max(max,prices[i]-curmin);            }            else{                curmin = prices[i];            }        }        return max;    }

0 0
原创粉丝点击