博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Best Time to Buy and Sell Stock II
阅读量:4660 次
发布时间:2019-06-09

本文共 982 字,大约阅读时间需要 3 分钟。

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

 

Analyse: Since we can complete as much as transactions as we can, we can add a small interval as long as this interval is increasing. Specifically, we define the interval as neighbours. 

Runtime: 8ms.

1 class Solution { 2 public: 3     int maxProfit(vector
& prices) { 4 if(prices.size() <= 1) return 0; 5 6 int result = 0; 7 for(int i = 1; i < prices.size(); i++){ 8 if(prices[i] > prices[i - 1]) 9 result += prices[i] - prices[i - 1];10 }11 return result;12 }13 };

 

转载于:https://www.cnblogs.com/amazingzoe/p/4743245.html

你可能感兴趣的文章