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.

Example 1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5

max. 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: 0

In this case, no transaction is done, i.e. max profit = 0.

读题

题目的意思就是给你一个数组,第i个元素表示第i天货物的价格,假定只允许进行一次交易,求最大的利润

源码地址

解题思路

要想获得最大的利润就是要低买高卖,也就是以最低的价格买入以最高的价格卖出,还要明确的是卖一定是在买之后。

可能会想到用两层循环解决这样的问题,但是会存在超时的情况,再者如果一个数组是递增的,那么你外层循环是没有意义的,如果一个数组是递减的,那么也不存在获利的情况,所有用两层循环去解决是不现实的。

我们要尽量使用O(n)时间复杂度去完成这样一个任务

价格波动.png

我们看这张图片,假定我们在a点买入,在b点卖出,那么我们在[a,b]之间就实现了当前的利润最大,那么如果我们在a点买入,c点卖出就是亏了,如果我们在c点之后的某时刻(价格高于a点的价格)卖出,这个时候在c点买入肯定要比在a点买入的利润大,明白了这一点就好办了,其实我们的任务就是找最低买入价

代码演示

package com.xiaoysec;

public class Solution121 {
    public int maxProfit(int[] prices){
        if(prices.length <= 1)
            return 0;
        //当前的最低买入价
        int minPrice = prices[0];
        int maxPrice = 0;
        //O(n)的时间复杂度
        for(int i=1;i<prices.length;i++){
            //如果当前的价格比最低价低就作为买入价
            if(prices[i]<minPrice)
                minPrice = prices[i];
            else
                //当前的价格高于买入价(最低价)就计算利润并与最大利润比较
                maxPrice = Math.max(maxPrice, prices[i]-minPrice);
        }
        return maxPrice;
    }
    
    public static void main(String[] args){
        int[] prices = {7, 1, 5, 3, 6, 4};
        Solution121 solution = new Solution121();
        int maxprofix = solution.maxProfit(prices); 
        System.out.println(maxprofix);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容