股票买卖问题-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天中最低买入价。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值