美文网首页
[数组]122. Best Time to Buy and Se

[数组]122. Best Time to Buy and Se

作者: Reflection_ | 来源:发表于2017-10-24 13:40 被阅读0次

题目:122. Best Time to Buy and Sell Stock ||

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).

给一数组,表示一个商品每天的价钱。每天可以选择买入或者卖出该商品,求最大的收益。

思路:只要第二天比前一天的价格高,那必然可以将差价算入收益。累加即可。

class Solution {
    public int maxProfit(int[] prices) {
        int days = prices.length;
        if(days == 0) return 0;
        int profit = 0;
        for(int i =1; i<days;i++){
            if((prices[i] - prices[i-1]) > 0) profit += (prices[i]-prices[i-1]);
        }
        if(profit <= 0) profit = 0;
        return profit;
    }
}

相关文章

网友评论

      本文标题:[数组]122. Best Time to Buy and Se

      本文链接:https://www.haomeiwen.com/subject/mxitpxtx.html