标签:
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.
解法1:
找到每个极小值,从每个极小值之后找一个最大值,计算最大收益。比较每个最大收益。
public class Solution { public int maxProfit(int[] prices) { if(prices == null || prices.length == 0 || prices.length == 1) return 0; int maxprofit = Integer.MIN_VALUE; int dateIn = 0; while(dateIn < prices.length - 1) { //find a bottom while(dateIn < prices.length - 1 && prices[dateIn] >= prices[dateIn+1]) dateIn++; for(int i=dateIn+1; i<prices.length; i++) { if(prices[i] - prices[dateIn] > maxprofit) { maxprofit = prices[i] - prices[dateIn]; } } //find a top while(dateIn < prices.length - 1 && prices[dateIn] <= prices[dateIn+1]) dateIn++; } return maxprofit == Integer.MIN_VALUE ? 0 : maxprofit; } }
解法2:
先整理数据,计算后一个元素相对前一个元素的差值,第一个元素为0,如1,4,2整理后为0,3,-2;
计算一个连续的数组元素的和,求和的最大值。
public class Solution { public int maxProfit(int[] prices) { if(prices == null || prices.length < 2) return 0; for(int i=prices.length - 1; i>0; i--) { prices[i] = prices[i] - prices[i-1]; } prices[0] = 0; int maxprofit = 0; int profit = 0; for(int i=0; i<prices.length; i++) { profit += prices[i]; if(profit < 0) { profit = 0; } else if(profit > maxprofit) { maxprofit = profit; } } return maxprofit; } }
LeetCode-121 Best Time to Buy and Sell Stock
标签:
原文地址:http://www.cnblogs.com/linxiong/p/4240086.html