标签:leetcode
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.
原题链接:https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock/
题目:假设你有一个数组,其中的第 i 个元素代表给定的第 i 天的股票价格。
如果你被允许至多完成一个交易(如,买一和卖一股票),设计一个算法找出最大的利润。
最Naive的解法,就是遍历所有的 后 - 前 ,找出最小值。超时了。
public static int maxProfit(int[] prices){ int len = prices.length; if(len <= 1) return 0; int max = 0; for(int i=0;i<len;i++){ for(int j=i+1;j<len;j++){ int profit = prices[j] - prices[i]; if(max < profit) max = profit; } } return max; }
public static int maxProfit(int[] prices){ int len = prices.length; if(len <= 1) return 0; int min = prices[0],max = 0; for(int i=1;i<len;i++){ int profit = prices[i] - min; if(max < profit) max = profit; if(min > prices[i]) min = prices[i]; } return max; }
LeetCode——Best Time to Buy and Sell Stock,布布扣,bubuko.com
LeetCode——Best Time to Buy and Sell Stock
标签:leetcode
原文地址:http://blog.csdn.net/laozhaokun/article/details/37699839