这些小活动你都参加了吗?快来围观一下吧!>>
电子产品世界 » 论坛首页 » 嵌入式开发 » STM32 » best-time-to-buy-and-sell-stock-ii

共1条 1/1 1 跳转至

best-time-to-buy-and-sell-stock-ii

高工
2018-01-25 12:09:53     打赏

Say you have an array for which the i thelement is the price of a given stock on dayi.

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天的价格,交易次数不限,但一次只能交易一支
股票,也就是说手上最多只能持有一支股票,求最大受益


思路:贪心算法
从前向后遍历数组,只要当天的价格高于前一天的价格,就算收益



[cpp] view plain copy
  1. class Solution  

  2. {  

  3.     int maxProfit(vector<int> &prices)  

  4.     {  

  5.         if (prices.size()<2)  

  6.         {  

  7.             return 0;  

  8.         }  

  9.   

  10.         int max = 0;  

  11.         for (int i = 1; i<prices.size(); i++)  

  12.         {  

  13.             int diff = prices[i] - prices[i - 1];  

  14.             if (diff>0)  

  15.             {  

  16.                 max += diff;  

  17.             }  

  18.         }  

  19.   

  20.         return max;  

  21.     }  

  22. };  




共1条 1/1 1 跳转至

回复

匿名不能发帖!请先 [ 登陆 注册 ]