算法题——Best Time to Buy and Sell Stock II(JAVA)Greedy

题目描述:
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).

读题:
1.某样货物每天的动态价格,设计算法来求出能够获得的最大的利润。(不要求计算具体交易顺序)
2.每天都可以买卖,但是要先卖了才能买。

知识储备:
贪心算法
定义:
贪心算法是指在对问题求解时,总是做出在当前看来是最好的选择。也就是说,不从整体最优上加以考虑,只做出在某种意义上的局部最优解。贪心算法不是对所有问题都能得到整体最优解,关键是贪心策略的选择,选择的贪心策略必须具备无后效性,即某个状态以前的过程不会影响以后的状态,只与当前状态有关。

解题思路:
1. 按照贪心算法,第二天只要能够盈利,就卖掉现货,获得利润。
2. 假设我昨天买入,今天会出现两种情况:
2.1 今天价格上涨了;于是马上卖出,获得利润,然后我可以重新买入,买入价=今天的价格
2.2 今天价格下降了;这时候不能卖出,假装我昨天没买,是今天才买入的。买入价=今天的价格。

提交代码:

public class Solution {
    public int maxProfit(int[] prices) {
        if (prices.length < 2) {
            return 0;
        }
        int profit = 0;
        int price = prices[0];
        for (int i = 1; i < prices.length; i++) {
            if (prices[i] > price) {
                profit += prices[i]-price;
            }
            price = prices[i];
        }
        return profit;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值