美文网首页
122.Best Time to Buy and Sell St

122.Best Time to Buy and Sell St

作者: ryderchan | 来源:发表于2017-03-29 13:50 被阅读15次

    题目如下:

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

    我的提交:

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

    由于交易次数不限,只要当天价格比前一天高,就进行交易。,这样便可保证收益最大,可使用贪心的思路解决。

    相关文章

      网友评论

          本文标题:122.Best Time to Buy and Sell St

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