leetcode 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.

题目分析

题目给出一个数组,数组中是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;

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值