best-time-to-buy-and-sell-stock

package com.ytx.array;
/**
 * 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 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.
       
       假设你有一个数组,里面存放的第i个元素表示第i天的股票的价格,如果你最多只允许进行一次交易(买进和卖出股票视为一次交易)
       请设计一个算法得到最大利润。
       
       思路:假设第i天卖出股票能得到最大利润,第i天价格为prices[i],那么买进股票应该是在第0~i天的价格是最小值的情况下,才有最大利润。
       遍历一遍就能找到所有第i天卖出股票获得利润中的最大值。
       也可以换用DP的思想来思考,思路是对于每个i都求出从0到i区间内的最大获益,而对于i+1只需要比较第i+1天的价格和前i天最低价的关系,
       就可以直接求出0到i+1天区间内的最大获益。也就是说对0到i天的最大获益的计算复杂度是O(1),总体复杂度是O(n)。
 * @author yuantian xin
 *
 */
public class Best_time_to_buy_and_sell_stock {
       
       //自己最初想的直接O(n2)的解法
       /*public static int maxProfit(int[] prices) {
             int maxProfit = 0;
             for(int i = 0; i < prices.length; i++) {
                    for(int j = i + 1; j < prices.length; j++) {
                           if( maxProfit < ( prices[j] -prices[i] ) ) {
                                 maxProfit = prices[j] -prices[i];
                           }
                    }
             }
        return maxProfit;
    }*/
       
       public static int maxProfit(int[] prices) {
             int len = prices.length;
             if( len == 0) return 0;
             int maxProfit = 0;
             int min_buy = prices[0];
             for(int i = 1; i < len; i++) {
                    //找到第0~i天买进股票最小花费的price
                    min_buy = Math.min(min_buy, prices[i]);
                    //那么prices[i] -min_buy就是第i天卖出得到的最大利润,再和之前的做比较,求所有中的最大值
                    maxProfit = Math.max(maxProfit, prices[i] -min_buy);
             }
             return maxProfit;
       }
       
       
       
       public static void main(String[] args) {
             int [] stock_prices = {2,1,2,0,1};
             System.out.println(maxProfit(stock_prices));
       }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值