zoukankan      html  css  js  c++  java
  • [LeetCode] 22. Best Time to Buy and Sell Stock II Java

    题目:

    Say you have an array for which the ith element is the price of a given stock on day i.

    Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

    题意及分析:假设有一个数组,它的第i个元素是一个给定的股票在第i天的价格。设计一个算法来找到最大的利润。你可以完成尽可能多的交易(多次买卖股票)。然而,你不能同时参与多个交易(你必须在再次购买前出售股票)。对于某天来说,如果第二天的价格高于当前价格那么就可以买,然后第二天卖出,收益为价格差,依次类推,直到倒数第二天,可以证明这样可以得到最大利润。所以可以直接从头到尾扫描prices,如果price[i] – price[i-1]大于零则计入最后的收益中,这就是贪心法。但是这个会违反“不能同一天买卖的规则”,例如3天的价格分别为1,2,3,那么按上述算法就会在2那天同一天买卖了。但是 正确的做法应该是: 第1天买第3天卖。虽然两种方法数字结果是对的,但是逻辑不一样。。

    代码:

    public class Solution {
        public int maxProfit(int[] prices) {
            if(prices.length==0||prices.length==1) return 0;
            int res=0;		
            for(int i=0;i<prices.length-1;i++){
            	if(prices[i+1]>prices[i])
            		res+=prices[i+1]-prices[i];
            }
            // System.out.println(res);
            return res;
        }
    }

    但是这样违反了题目说的不能在同一天包含买入和卖出,所以可以先找到递减的局部最低点,再找到递增的局部最高点,算一次加和,然后再这么找。这样就能保证买卖不会在同一天了。。

    代码:

    public class Solution {
        public static int maxProfit(int[] prices) {
            int len = prices.length;
            if(len <= 1)
                return 0;
            int total=0;		//总收入
            int i=0;		//当前所在位置
            
            while(i<len-1){
            	int buy,sell;		//记录买入卖出时间
            	while(i<len-1&&prices[i+1]<prices[i]){		//找到局部最小点
            		i++;
            	}
            	buy=i;		//买入点
            	i++;		//卖出点至少在买入点的下一个点
            	while(i<len&&prices[i]>=prices[i-1]){  //找到局部最大点
            		i++;
            	}
            	sell=--i;	//卖出点
            	total +=prices[sell]-prices[buy];
            }
            return total;
        }
    }
    

      

      

      

      

  • 相关阅读:
    【LSGDOJ 1408】邮局
    中间件小姐姐直播“带货”——阿里程序员必知的插件
    ChaosBlade 发布对 C++ 应用混沌实验的支持
    来自 Spring Cloud 官方的消息,Spring Cloud Alibaba 即将毕业
    大合集 | 9 场 Dubbo Meetup 回顾视频和PPT下载
    Future Maker | 领跑亚太 进击的阿里云数据库
    更简单易用的数据仓库,阿里云重磅推出分析型数据库3.0版
    AnalyticDB for MySQL 3.0 技术架构解析
    阿里云 EMAS HTTPDNS 联合函数计算重磅推出 SDNS 服务,三大能力获得突破
    新一代互联网传输协议QUIC浅析
  • 原文地址:https://www.cnblogs.com/271934Liao/p/7057954.html
Copyright © 2011-2022 走看看