[LeetCode]121. Best Time to Buy and Sell Stock

121. Best Time to Buy and Sell Stock

一、题目

Problem Description:
Say you have an array for which the i t h i^{th} ith element is the price of a given stock on day i i i.
If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Example 1:
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 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
Explanation: In this case, no transaction is done, i.e. max profit = 0.

二、题解

  • 最多交易一次(即买入和卖出一支股票),获得最大利润
  • 注意:不能在买入股票前卖出股票;卖出价格要高于买入价格

2.1 Approach #1 : Brute Force

在一个数组中找到差值最大(利润最大)的两个数,且第二个数(卖出价格)要高于第一个数(买入价格)

变量buy表示买入股票的日子;变量sell表示卖出股票的日子
sell = buy + 1;表示至少在买入股票第二天才能卖出股票,即 cannot sell a stock before you buy one

Time complexity : O ( n 2 ) O(n^2) O(n2).
Space complexity : O ( 1 ) O(1) O(1).

//Brute Force
//Time complexity : O(n^2); Space complexity : O(1)
class Solution {
    public int maxProfit(int[] prices) {
		int res = 0;//maxProfit
		for(int buy = 0; buy < prices.length; buy++){
			for(int sell = buy + 1; sell < prices.length; sell++){
				int profit = prices[sell] - prices[buy];
				res = profit > res ? profit : res;
			}
		}
		return res;
    }
}

2.2 Approach #2 : Dynamic Programming

思路:
动态找到当前最低价格后的最高价格,比较各天利润,输出最大利润。
设置两个变量:用minPrice表示当前最低价格;用maxProfit表示当前获得的最大利益,即(卖出价格-minPrice)的最大值。

Time complexity : O ( n ) O(n) O(n)
Space complexity : O ( 1 ) O(1) O(1)

//Dynamic Programming
//Time complexity : O(n); Space complexity : O(1)
class Solution {
    public int maxProfit(int[] prices) {
		int minPrice = Integer.MAX_VALUE;
		int res = 0;//maxProfit
		for(int i = 0; i < prices.length; i++){
			if(prices[i] < minPrice){
				minPrice = prices[i];
			}else if(prices[i] - minPrice > res){
				res = prices[i] - minPrice;
			}
			/*
			else{
				//res = (prices[i] - minPrice) > res ? (prices[i] - minPrice) : res;
				res = Math.max(res, (prices[i] - minPrice));
			}
			*/
		}
		return res;
    }
}

2.3 Approach #3 : Kadane

  • Kadane算法
    Kadane算法就是为了解决最大子数组之和这一问题。
    Kadane算法相关的知识在之前的博客中有详细介绍,不明白的可以先浏览这篇博客 [LeetCode]53. Maximum Subarray(暴力穷举+Dynamic Programming+Kadane)
    Kadane算法是在DP基础上的进一步优化。也可以将Kadane看作是DP算法的一个应用。
    简单说,如果dp[i]只依赖于dp[i-1],且后续也用不到dp[]数组,就可以只用一个变量代替dp[i]。Kadane算法说白了其实就是用一个变量代替了dp[]数组,节省了空间

  • 解题思路
    所求maxProfit为其中两天价格之差,假设maxProfit = nums[3] - nums[1],可以把其转换为相加的形式:nums[3] - nums[1] = (nums[2] - nums[1]) + (nums[3] - nums[2]), (nums[2] - nums[1]) 、(nums[3] - nums[2])看做一个整体,即数组的一个元素,原问题转化为求最大子数组之和的问题,之后可以用Kadane算法进行求解。
    人为将给定数组转换为Kadane需要用到的数组形式,即将原问题转化为最大子数组之和的问题,接着用Kadane算法对新其求解。

  • 解题步骤

  1. 通过prices[i-1] = prices[i] - prices[i-1];关系式将原问题转换为求最大子数组之和的问题;
  2. 用Kadane算法求解,求解出的最大子列之和即为原问题的最终结果

Time complexity : O ( n ) O(n) O(n)
Space complexity : O ( 1 ) O(1) O(1)

//Kadane
//Time complexity : O(n); Space complexity : O(1)
class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length <= 1) return 0;
        // 人为将给定数组转换为Kadane需要用到的数组形式:[7,1,5,3,6,4]->[-6,4,-2,3,-2,4(舍)],后续即为求最大子列和
        for(int i = 1; i < prices.length; i++){
            prices[i-1] = prices[i] - prices[i-1];
        }
        //如上示例所示,转换后的prices[]数组最后一个元素舍去,所以endIndex=prices.length-2
        int res = maxSubarray(prices, 0, prices.length - 2);//maxProfit;
        return res > 0 ? res : 0;//[7,6,4,3,1]->[-1,-2,-1,-2,1(舍)] return 0
    }
    //用Kadane算法解决最大子数列和的问题
    public int maxSubarray(int[] nums, int startIndex, int endIndex) {
        //采用Kadane求数组的最大子列和
        int maxSum = nums[startIndex];
        int subSum = nums[startIndex];
        for(int i = startIndex + 1; i <= endIndex; i++){
            subSum = nums[i] + Math.max(subSum, 0);
            maxSum = Math.max(maxSum, subSum);
        }
        return maxSum;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值