题目内容
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.
题目分析
题目给出一个数组,数组中是int型数字,为股票一天内的价格。只允许最多操作一次事务(低价买,高价卖),从而求出获利最大的情况。
我们的思路很简单,就是低价买,高价卖由股票自身的特点得到,必须先买入,然后才能卖出。所以说,选得低点的值必须在高点值的前面才能执行,否则将无法执行。因此,我们将面临如下的样例情况:
- 最高点的值在最后位置: 1,2,3,4,5,6 或者 2,1,3,4,5,6,min=1,max=6,profit=5;
递减的排序: 6,5,4,3,2,1.profit=0
最高点在前面的排序:4,1,2
所以解决了这三种情况,即可。
方法:遍历数组,遍历过程中找到min和max,在找到min和max过程中,同时标记他们的位置,minflag,maxflag,并计算当前情况下的profit。当min更新了,maxflag的值,更新为minflag的值,max变为min
public class Solution {
public int maxProfit(int[] prices) {
int min=0,max=0,profit=0,minFlag=0,maxFlag=0;
for (int i = 0; i < prices.length; i++) {
if(i==0)
{
min=prices[0];max=prices[0];profit=0;continue;
}
if (min>prices[i]) {
min=prices[i];
minFlag=i;
max=prices[i];
}
if (max<prices[i]) {
max=prices[i];
maxFlag=i;
}
if(minFlag<maxFlag){
int tem=max-min;
if(tem>profit) profit=tem;
}
}
return profit;
}
}