leetcode #122 in cpp
2016-06-19 07:13
417 查看
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).
Solution:
It is similar to #121. We add all sum of increasing sublist into the profit.
Code:
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.empty()) return 0;
int cost = prices[0];
int price = prices[0];
int profit = 0;
for(int i = 1; i < prices.size(); i ++){
if(prices[i] < price){
profit+= price - cost;
price = prices[i];
cost = prices[i];
}else{
price = prices[i];
}
}
profit += price - cost;
return profit;
}
};
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).
Solution:
It is similar to #121. We add all sum of increasing sublist into the profit.
Code:
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.empty()) return 0;
int cost = prices[0];
int price = prices[0];
int profit = 0;
for(int i = 1; i < prices.size(); i ++){
if(prices[i] < price){
profit+= price - cost;
price = prices[i];
cost = prices[i];
}else{
price = prices[i];
}
}
profit += price - cost;
return profit;
}
};
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- C++中const用法总结
- CPP 虚函数、虚函数表及虚拟继承(转)
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- Deploying Control Plane Policing
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解