Say you have an array
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).
prices
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 (i.e., buy one and sell one share of the stock multiple times).
Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
Example 1:
Input: prices={7,1,5,3,6,4}
Output: 7
Approach
Java
public class BestTimeBuySellStockII {public static void main(String[] args) {int prices[] = { 7, 1, 5, 3, 6, 4 };System.out.println(maxProfit(prices));}static int maxProfit(int[] prices) {if (prices.length == 0)return 0;int sell, buy, profit = 0;int i = 1, j = 1;while (i < prices.length) {if (prices[i] < prices[i - 1])i++;else {j = i;break;}}if (i == prices.length)return 0;else {buy = prices[i - 1];sell = prices[i];if (j == prices.length - 1)return sell - buy;for (i = j + 1; i < prices.length; i++) {if (prices[i] > sell)sell = prices[i];if (i == prices.length)profit = sell - buy;else {profit += sell - buy;buy = prices[i];sell = prices[i];}}}return profit;}}
C++
#include <bits/stdc++.h>using namespace std;int maxProfit(vector<int>& prices){if(prices.size()==0)return 0;int sell,buy,profit=0;int i=1,j=1;while(i<prices.size()){if(prices[i]<prices[i-1])i++;else{j=i;break;}}if(i==prices.size())return 0;else{buy=prices[i-1];sell=prices[i];if(j==prices.size()-1)return sell-buy;for(i=j+1;i<prices.size();i++){if(prices[i]>sell)sell=prices[i];if(i==prices.size())profit=sell-buy;else{profit+=sell-buy;buy=prices[i];sell=prices[i];}}}return profit;}int main(){vector<int> prices={7,1,5,3,6,4};cout<<maxProfit(prices);return 0;}
No comments:
Post a Comment