首页 > 学院 > 开发设计 > 正文

LEETCODE--Best Time to Buy and Sell Stock II

2019-11-14 10:43:44
字体:
来源:转载
供稿:网友

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(vector<int>& prices) { int len = prices.size(); int profit = 0; for(int i = 1; i < len; i++){ profit += max(prices[i]-prices[i-1], 0); } return profit; }};

方法二:略麻烦

class Solution {public: int maxProfit(vector<int>& prices) { int i = 0; int j = 1; int len = prices.size(); int profit = 0; int pre; while(j < len){ pre = prices[j-1]; if(pre < prices[j]){ j++; if(j == len) profit += prices[j-1] - prices[i]; }else{ cout << pre << endl; profit += pre - prices[i]; i = j; j++; } } return profit; }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表