leetcode| Best Time to Buy and Sell Stock II

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天,里面的元素表示该天股票的价格,问你怎么选择时间节点买入卖出才能受益最大,算出最大收益

思路:这个题目的提示关键词有一个 Greedy,同样是有道后知道这个是贪心的意思,而后知道这个是专业术语叫贪心算法,大概意思是,不管之后的情况,只考虑当前状态的处理最佳就行,十分之符合现实,因为今天之后的股票价格走势散户们哪里知道啊,今天之前的是可以知道的。。。题目出的很现实,代码实现我们也是这样处理的,只要今天比昨天价格高,我们就买,之后价格多高不管,一言蔽之,见好就收

public int maxProfit(int[] prices) {
  int res = 0,len = prices.length,price = 0;
   for(int i = 0;i<len-1;i++){
    price = prices[i+1]-prices[i];
    if(price>0){
      res+=price;
    }
    }
    return res;
  }

 

posted @ 2016-07-20 10:28  Roger's  阅读(111)  评论(0编辑  收藏  举报