leetcode数组专项习题:股票买卖问题-I

2、买卖股票的最佳时间
best-time-to-buy-and-sell-stock: Say you have an array for which the i th element is the price of a given stock on day ith. 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.
题目要求:给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。设计一个算法来计算你所能获取的最大利润。你最多只可以完成一笔交易(进行一次买入卖出)。
分析:首先,股票的利润来自于买入和卖出的差价,如买入时为5,选择在9时卖出,利润为4.当只有一次交易时,最大利润必然是买入和卖出的最大差值。最直观的方法就是“蛮力”求解,逐一计算数组中所有元素的差值,选取差值最大的即可(注意卖出一定在买入之后)。该算法的时间复杂度为O(n^2)。

public class Solution{
// 用于测试,在提交代码的时候可以不用加
    public static void main(String[] args) {
    	Solution gupiao=new Solution();
    	int[] prices= {1};
    	int price=gupiao.maxProfit(prices);
    	System.out.println(price);
    }
    public int maxProfit(int[] prices) {
        int len=prices.length;
        int[] profit=new int[len];
        int lirun=0;
        int maxnums=0;
    	for(int i=0;i<len;i++)
    	{
    		for(int j=i+1;j<len;j++)
    		{   
    			if(maxnums<prices[j])
    			{
    				maxnums=prices[j];
    			}
    			
    		}
			profit[i]=maxnums-prices[i];
			maxnums=0;
    	}
    	for(int i=0;i<len-1;i++)
    	{
    		if(lirun<profit[i])
    		{
    			lirun=profit[i];
    		}
    	}
    	return lirun;
    }
}

算法改进思路:上述算法显然过于复杂了,需要作出改进。我们可以定义profit(i)为卖出价为数组中第i个数字时可能获得的最大利润,当卖出价i固定时,可能的最大利润必然来自于前i-1天中最低买入价。

猜你喜欢

转载自blog.csdn.net/weixin_43277507/article/details/88092884
今日推荐