Quesion :
Say you have an array for which theithelement 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).
for example: array[] = { 2, 5, 3, 8, 9, 4 } , maxProfit = (9-8) + (8-3) + (5-2) = 1 + 5 + 2 = 8.
Anwser 1: :
class Solution {
public:
int maxProfit(vector<int> &prices) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(prices.size() == 0) return 0;
int len = prices.size();
int ret = 0;
for(int i = len - 1; i > 0; i--){
if(prices[i] > prices[i-1]){
ret += prices[i] - prices[i-1];
}
}
return ret;
}
};
分享到:
相关推荐
《最佳买卖股票时机II》是LeetCode中的一道经典编程题目,主要涉及动态规划和数组操作的知识点。在这个问题中,我们被赋予一个整数数组`prices`,表示某支股票每天的价格。任务是找到在允许进行多次交易的情况下,...
java java_leetcode题解之Best Time to Buy and Sell Stock II.java
java java_leetcode题解之Best Time to Buy and Sell Stock with Cooldown
java java_leetcode题解之Best Time to Buy and Sell Stock IV.java
java java_leetcode题解之Best Time to Buy and Sell Stock III.java
java java_leetcode题解之Best Time to Buy and Sell Stock I.java
python python_leetcode题解之122_Best_Time_to_Buy_and_Sell_Stock_II
python python_leetcode题解121_Best_Time_to_Buy_and_Sell_Stock
leetcode LeetCode 解决题目的总数: 136/1753 微信公众号: 工程师Ruojhen 算法-动态规划 题号 名称 English Name 题解 53 最大子序和 Maximum Subarray 70 爬楼梯 Climbing Stairs 121 买卖股票的最佳时机 Best Time...
javascript js_leetcode题解之122-best-time-to-buy-and-sell-stock-ii.js
leetcode leetcode-java leetcode刷题笔记 已做题目列表 1.Two Sum 3.Longest Substring Without Repeating Characters 5.Longest Palindromic Substring 20.Valid Parentheses 26.Remove Duplicates from Sorted ...
python python_leetcode题解之123_Best_Time_to_Buy_and_Sell_Stock_III
javascript js_leetcode题解之121-best-time-to-buy-and-sell-stock.js
javascript js_leetcode题解之123-best-time-to-buy-and-sell-stock-iii.js
股票收益leetcode LeetCode 股票问题 Best Time to Buy and Sell Stock (Easy) 一次交易,找最大收益 for i in prices: low = min(low, i) profit = max(profit, i-low) Best Time to Buy and Sell Stock II (Easy) ...
- Best Time to Buy and Sell Stock II:不限制交易次数,寻找最大利润。 - Best Time to Buy and Sell Stock III:存在多日限制交易,最多两次交易。 - Best Time to Buy and Sell Stock IV:与前三者不同,可能...
Leetcode的ac是什么意思 LeetCodeInJava List #98 Validate Binary Search Tree #100 Same Tree #104 Maximum Depth of Binary Tree #122 Best Time to Buy and Sell Stock II #136 Single Number #150 Evaluate ...
第二个问题“Best Time to Buy and Sell Stock II”(122题),题目条件相同,但允许进行多笔交易。在一次交易中,买入后再卖出才算是完成了一笔交易,且不能同时买入多股股票。此问题可以用贪心算法解决,即遍历...
leetcode 分类 LeetCode LeetCode Java Solution 2018年5月31日 更新 最近刷了一遍 LeetCode,发现第一次的代码确实有些 low 很多代码并不简洁,本来1行的代码可以写成3行 思维混乱 没有按照题目类型分类 没有写结题...
63. 股票的最大利润题目链接Leetcode:121. Best Time to Buy and Sell Stock题目描述可以有一次买入和一次卖出,买入必